Search code examples
cfunctionscopeglobal-variablespass-by-value

Question about call by value in C language


When I run this program, it outputs 10 20 (first snippets of code).

#include <stdio.h>

int x = 10;
int y = 20;

int main()
{
    fun(x, y);
    printf("%d %d", x, y);
}

int fun(int x, int y)
{
    x = 30;
    y = 40;
}

But when I write it as this:

#include <stdio.h>

int x = 10;
int y = 20;

int main()
{
    fun(x, y);
    printf("%d %d", x, y);
}

int fun(int n1, int n2)    // I include other variables except from global variable.
{
    x = 30;
    y = 40;
}

it outputs 30 40. I want to know why it modifies the global variables only second code snippets even though without using pointers? and why first one is not? if anyone suggest me reference for this theory part I would be great full.

I want to learn these theory parts correctly because I am new to programming.


Solution

  • In the first code snippet, the fun function receives the parameters x and y by value, which means that the function creates its own local copies of those variables. Any modifications made to these local copies do not affect the original global variables x and y defined outside the main function. Therefore, when you print x and y in the main function after calling fun, their values remain unchanged, resulting in "10 20" being printed.

    In the second code snippet, you're using the same variable names x and y as the global variables inside the fun function. This creates ambiguity because the function parameters n1 and n2 have the same names as the global variables. In this case, when you assign values to x and y inside the fun function, it modifies the global variables themselves because they have the same name. This is called shadowing, where the local variables shadow the global variables with the same name. As a result, when you print x and y in the main function after calling fun, you see the modified values "30 40" because the global variables were directly modified within the function.

    To avoid confusion and potential issues like this, it is generally recommended to use different names for local variables in functions to clearly distinguish them from global variables. This helps improve code readability and avoids unintentional modifications to global variables.

    For further understanding of variable scope and shadowing, you can refer to C programming language textbooks or online resources that cover these topics in detail. Some recommended resources include "The C Programming Language" by Brian Kernighan and Dennis Ritchie or websites like tutorialspoint.com or cplusplus.com.