Michael Wu
Michael Wu

Reputation: 3

Issue with scope of variables in C, why a function prints what it's supposed to print

What exactly is going on in this program here? Why does myFunction print 3 for x?

int myFunction(int);

void main(void)     /* local variables: x, result in main */
{
    int result, x = 2;
    result = myFunction(x);
    printf("%i", result); /* prints "3" */
    printf("%i", x); /* prints "2" */
}

int myFunction (int x)
{
    x = x + 1;
    printf("%i\n", x); /* prints "3" */
    return x;
}

Upvotes: 0

Views: 34

Answers (2)

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

You should read about the differences between pass by value vs. pass by reference in function variables (see here).

In your case, you are passing x by value to myFunction, the function basically gets the value of x (2) and increments it, but never changes the original value of x from your main function.

Upvotes: 0

Guffa
Guffa

Reputation: 700790

That's because the parameter is a local variable in the function.

When the function is called, there is space allocated on the stack for the parameter, and the value from the variable x is copied into the parameter.

In the function the parameter x is a local varible, separate from the variable x in the calling code. When x is increased in the function, that only happens to the local copy.

When the function ends, the parameter goes away when the stack frame for the function is removed from the stack.

Upvotes: 1

Related Questions