What is the effect of x=x++;? [duplicate] - c

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 9 years ago.
#include <stdio.h>
int main()
{
int x=100;
x=x++;
printf("x : %d\n",x); //prints 101
return 0;
}
What is the reason for output 101? I think output should be 100.

This is Undefined Behaviour, due to Sequence Points.
Between consecutive "sequence points" an object's value can be
modified only once by an expression
The end of the previous epxression x=100; is one sequence point, and the end of x=x++; is another.
Basically, your expression has no intermediate 'sequence points', yet you're modifying the value of X twice. the result of this is Undefined Behaviour: Basically, anything could happen: You could get 100, 101 or 42...

Here is what I believe you're looking for:
int main(){
int x=100;
printf("x : %d\n",x++); // Will print 100 and then increment x
return 0;
}

You're incrementing x before printing it - so this is the reason for the output 101.
You're doing the same operations as x = x; x++;

You're incrementing x after assigning it to x, effectively:
The x=x++ effectively becomes (assign x to x prior to increment) then (increment x)
This is going to give the same effect as if you were to wrote:
x = x;
++x; // Increment after the assignment
This should leave x as 101 after the x=x++; line.

You're incrementing the same x you're printing - here it doesn't matter whether post- or pre-incrementing.
x=x++ would produce the same result as x=++x.
If you would like to assign it another object do this:
#include<stdio.h>
int main(){
int x=100;
int y=x++;
printf("y : %d\n",y); //prints 100
printf("x : %d\n",x); //prints 101
return 0;
}

This is what is happening
#include <stdio.h>
int main()
{
int x=100;
x=x++; // This is original code however I have rewritten this as below
x=x;
x++;
printf("x : %d\n",x); //prints 101
return 0;
}
as you can see
x=x++;
can be rewritten as
x=x;
x++;
hence the result no surprises ...

The effect is that the value of x won't change.
x++ works like this:
Take a reference of the value.
Allocate a new integer and store the value into it.
Increment the reference.
Return the temporary integer.
In C++ it would look like this:
int PostIncrement(int& x)
{
int y = x;
x = x + 1;
return y;
}
The operator precedence is not lost in this way and the assignment is done after the increment.

Related

What is the different effect of assigning to vs. initialising static variables in a function?

#include <stdio.h>
int print1(void)
{
static int x= 10;
x+=5;
return x;
}
int print2(void)
{
static int x;
x = 10;
x+= 5;
return x;
}
int main()
{
int x;
x = print1();
x+= print1();
x+= print2();
x+= print2();
printf("%d", x);
return 0;
}
My solution:
First in print1 statement the value of the will increment by 5 , x will be 15 .
Then upon calling print1 function for the 2nd time it will be 15+5=20, since it will hold the previous value.
Now for the function print2, it will again initialise the x value with 10, then increment it by 5. Value of x will be 15.
for the last statement value of x will be 15+5=20.
x=15+20+15+20=70
But the answer is 65. Please correct me where did I go wrong? I even wrote it in my compiler, it is giving output 65, but if change the position of x inside Print2 statement like static int x=10, it is giving different output?
Why this is happening?
The init of a static variable like static int x=10; only happens once per program execution. And that is not like a statement being executed, it is during setup of variables for the program.
The assignment statement x = 10; is executed each time the function is executed.
This means the two code versions you discuss are different and especially have different effects on variable values; which in turn explains the different output.

Does adding values to a variable in printf() change the overall value of x?

int main() {
x=5;
printf("%d",x+3);
}
x could be either 5 or 8 after this example (I know that the output on the screen would be 8.)
The value at the address of x remains unchanged in this example. Inside the printf, we first get the value at the address of x and then add it to 3 and output it to the screen.
This is why we use statements like x=x+3 to change the value.
This kind of thing doesn't exist. What's best to do is to perform the operation outside of the printf() function:
#include <stdio.h>
int main() {
int x = 5;
x += 3; // x = x + 3
printf("%d\n", x);
}
According to Tomo Ceferin, x won't change because of the language's logic.
This works in C99. Not sure if any other version does.
#include <stdio.h>
int main() {
int x = 5;
printf("%d\n", x += 3);
}
Your program does not compile because there is no definition for x.
You should also include <stdio.h> to declare printf properly.
The statement printf("%d", x + 3); does produce 8 on standard output, but it does not modify the variable x, assuming x is defined as int x; somewhere.
You could modify x inside the call to printf: this has always been supported by the C language, although it is considered confusing.
#include <stdio.h>
int main() {
int x = 5;
printf("%d\n", x += 3); // prints 8 with a side effect
// x now has a value of 8
printf("%d\n", x); // prints 8 again
return 0;
}
The value of x remains the same, because you do not change it at all. Also, you should take into account to declare what type of data is your variable.
For example:
int main(){
int x = 5; //this is the variable x, declared as an integer. Its value is 5.
printf("%d", x + 3) //here you print an integer variable which has the value of (x+3),
//(5 + 3 = 8), to be more precise. (this instruction has nothing to
//do with the value of x, because you're not changing x in any way.)
}
So you will get on the screen the value of 8.
Hope it helped.

Constant variable in C

I'm running a simple code to test my understanding, as of below.
The output that I got from this is actually 10.
I thought that the output should gave me a compile error, as "b" couldn't be add to x, as x is a const variable.
Can someone help to clear my understanding on this?
int aFunction(const int x){
return (x+10);
}
int main(){
int b =0;
b = aFunction(b);
printf("%d\n",b);
return 0;
}
This line
return (x+10);
Doesn't add 10 to x and return it. It forms the value that is x+10 and returns that but leaves x itself unchanged.
If you wrote
int c;
c=x+10;
Would you expect x to be increased by 10 after that second line executes?
Try
int aFunction(const int x){
int c=(x+10);
printf("aFunction: x=%d c=%d\n",x,c);
return c;
}
Basically, applying the const qualifier to a variable prevents the value of the variable from being modified.
In your function, aFunction(), the variable x is given a const qualifier which prevents the value of x from being modified in your function. There is no reason why your code shouldn't be able to compile since all the function is doing is returning a value which is 10 more than x. It is not in any way modifying the value of x.
If you did something like x += 10 which is short for x = x + 10, then you will get some compiler errors.
const int x only means that x itself cannot be changed inside the function. It has nothing to do with the return value.
Simple:
x is not changed until or unless you re-initialize it, look into these lines :
const int x : means X will never be changed.
x+10 : means just add 10 in X but never save the status.
x = x +10 " means overwrite the value of x which will Crash: and you will get desired Error

Static Variable re-initialization solution

Static variable re initialization:In the second part of the code i reinitialize the static variable x to 5. o/p of the first code is as expected but why o/p of the second part is 6 6 why not 6 7.
void foo()
{
static int x ;
x++;
printf("%d", x);
}
int main()
{
foo();
foo();
return 0;
}
//output will be 1 2
//But if i re initialize the static variable then why the output is like this:
void foo()
{
static int x ;
x=5;
x++;
printf("%d", x);
}
int main()
{
foo();
foo();
return 0;
}
//output is 66 why not 67
The result of:
x = 5;
x++;
is that x is 6. Since you execute this code twice you get the output 66.
Note, x = 5; is an assignment, not an initialization.
The output is 6, 6 because you reinitialize it to 5 each time you call the function.
To initialize it only once (and get 6, 7) you need to write:
static int x = 5;
Furthermore, the first code may yield unexpected results, because the variable is uninitialized and may contain any value.
The result is as expected because, in the function foo(),
void foo()
{
static int x ;
// what ever be the value of x until this point is retained.
// But what you are trying to do is assign the variable x again to 5, which means
// you are overwriting the previous value of x with 5.
x=5;
x++;
// Since x is always 5 due to overwriting, x++ will always yield "6" no matter what.
printf("%d", x);
}
In this scenario, the keyword static does not have any effect on the output.
void foo()
{
static int x ; // point 0
x=5; // point-1
x++; // point -2
printf("%d", x); // point- 3
}
int main()
{
foo(); // exe-1
foo(); // exe-2
return 0;
}
The program execution flow and the value of x at that point
Irrespective of how many times foo() is called, point-0 will be called only once.
exe-1: (point-0)x=0--> (point-1)x=5 (assigned) --> (point-2)x= 6
current value of x=6 before exe-2
exe-2: this time it doesn't comes to point-0, it comes to point-1, which is overwritting the current value of x(which is 6) with 5 again. So, after this, when it comes to point-2, the value of x is incremented from 5 to 6, so it prints 6

pre-increment and post-increment in printf

int main()
{
int value = 4321;
int *ptrVal = &value;
printf("%d %d",++value,(*(int*)ptrVal)--);
return 0;
}
How does pre-increment/post increment works in above print statement ?
And why is answer 4321 4321 ?
You are modifying the object value twice between two sequence points: you are invoking undefined behavior. Undefined behavior means your program can print 4321 4321, print 42 or even just crash.
A correct version of your program would be:
int value = 4321;
int *ptrVal = &value;
++value;
(*ptrVal)--; // no need to cast to int *
printf("%d %d", value, *ptrVal); // same as printf("%d %d", value, value);
Of course you don't need any temporary pointer to achieve this.
The code above is just broken. It is unspecified how it will work or what the answer will be. You need a sequence point between modifications or modifications and accesses.

Resources