ryank ryank - 5 months ago 57
C Question

Does printf alter variables?

I am not sure if incrementing a variable within a printf statement saves the valuable to a variable or not.

int x = 0;

printf("x=%d\n", ++x);
printf("x=%d\n", x);

Would the output be




I never learned the basics of C and want to know how it matches up to C++.

I do understand the pre/post increment but I am worried that doing ++x inside the first printf() won't save if I am incrementing it in the scope of a function.


The output will be 1.

Your expression ++x will be

x = x+1;

In both the printf() you get 1

So the value of x is modified with the pre-increment operator here and in printf() in the second line prints the new value of x which is 1

printf() just prints the value of x it doesn't modify your variable

Note the difference between pre-increment and post-increment .

With post-increment you will get 0 in the first printf() because the value of x is fetched by the printf()'s %d and later x gets incremented leading to the value of x in the second prinf() to be 1