Reputation:
#include <stdio.h>
int inc1(int x) { return x++; }
int inc2(int *x) { return (*x)++; }
int
main(void)
{
int a;
a = 3;
printf("%d\n", inc1(a) + a);
printf("%d\n", inc2(a) + a);
return 0;
}
I'm working through a past paper and one of the questions is to track the changes made to a between lines 6 and 9. I kind of understand pointers (referencing to memory location) but if someone could just talk me through the changes made to a throughout this piece of code that would be great.
Upvotes: 1
Views: 1717
Reputation: 1009
The line calling inc1() will print '6' (3+3) [first 3 is from the inc1(), due to post increment operator the incremented value is not returned]. Also since the inc1() called by value, value of 'a' is not affected outside the function.
Now, if the statement of calling inc2() in the paper is as following:
printf("%d\n", inc2(a) + a);
then your code will compile (hoping that you will store a memory location in 'a') but depending on the value in it (in case 'a = 3') at runtime you will get Segmentation Fault, since you are trying to dereference the memory location 3 which is not supposed to be accessed by your program.
Alternatively, if the statement is as following:
printf("%d\n", inc2(&a) + a);
then inc2() will increment the value of 'a' through pointer (address) but will return old value of 'a' (3) still due to its using post increment operator, but it will increment 'a' anyway and any subsequent access to 'a' will get the new value. The next 'a' will have value '4' because of evaluation is done from left to right, hence it will print 7 (3+4).
I hope it clarifies the difference between pointer and variable in C.
Upvotes: 0
Reputation: 11566
I'll explain this nearly identical code that doesn't contain the error in your post:
#include <stdio.h>
int inc1(int x) { return x++; }
int inc2(int *x) { return (*x)++; }
int main(void) {
int a;
a = 3;
printf("%d\n", inc1(a) + a);
printf("%d\n", inc2(&a) + a);
return 0;
}
a
is initialized to 3, then the value of a is passed to inc1()
, which returns it and adds 1 using post-increment. This means the actual value returned is still 3.
Next, the address of a is passed to inc2()
. That means that what happens to the value in x happens to a. Again, post-increment is used, so what inc2()
returns is 3, but after the call, a
is 4.
However, compilers are free to evaluate expressions, such as a
or inc2(&a)
, in any order between sequence points. This means that the a
on the right of inc2(&a) + a
may be either 3 or 4 (depending on whether a
is evaluated before or after int2(&a)
, so the program may output either 6 7 or 6 6.
Upvotes: 3