Incrementing in C

J

jobo

Suppose I have a function foo:

void foo(int x, int y) {

printf(" %d ", y);
x = y;


}

I have two ints a and b.
a = 7;
b = 7;
then I call foo(a, ++b);

For some reason at the end of running foo, I get a = 7 and b = 8.

Why do I not have a = b = 8?

Thank you much!
 
T

T.M. Sommers

jobo said:
Suppose I have a function foo:

void foo(int x, int y) {

printf(" %d ", y);
x = y;


}

I have two ints a and b.
a = 7;
b = 7;
then I call foo(a, ++b);

For some reason at the end of running foo, I get a = 7 and b = 8.

Why do I not have a = b = 8?

Because x is local to the function foo. In C function arguments
are passed by value, not by reference. If you want a function to
change an object in the calling function, you must pass in a pointer:

void foo(int *x, int y)
{
*x = y;
}

and call it:

int a, b;
....
foo(&a, b);
 
C

Chris Dollin

jobo said:
Suppose I have a function foo:

void foo(int x, int y) {

printf(" %d ", y);
x = y;
}

The assignment of `y` to `x` is pointless; `x` is a local
variable that will evaporate when `foo` returns.
I have two ints a and b.
a = 7;
b = 7;
then I call foo(a, ++b);

For some reason at the end of running foo, I get a = 7 and b = 8.

Well, yes. You assigned `7` to `a` and `b` and incremented `b`.
Calling `foo` doesn't change that.
Why do I not have a = b = 8?

Because the assignment of `y` to `x` is pointless; `x` is a local
variable that will evaporate when `foo` returns.
 
?

=?ISO-8859-1?Q?=22Nils_O=2E_Sel=E5sdal=22?=

jobo said:
Suppose I have a function foo:

void foo(int x, int y) {

printf(" %d ", y);
x = y;


}

I have two ints a and b.
a = 7;
b = 7;
then I call foo(a, ++b);

For some reason at the end of running foo, I get a = 7 and b = 8.

Why do I not have a = b = 8?

C passes values. When you call 'foo', the values in your a and b
variables are "copied" to the variables x and y. After that there's no
relation between a,b and x,y.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top