my code is :
code(){
int x=7;
x=x++;
output x; //prints 8 in C, prints 7 in Java
}
Guys the above code: prints 8
in C
, and 7
in Java
!!
Why is this so? please explain.
my code is :
code(){
int x=7;
x=x++;
output x; //prints 8 in C, prints 7 in Java
}
Guys the above code: prints 8
in C
, and 7
in Java
!!
Why is this so? please explain.
That will print 7
in Java. x=x++;
is equivalent to :
int temp = x;
x = x + 1;
x = temp;
The result would have been different if you would have used prefix operator , ++x
.
See for yourself over here: java code; C code.
Read Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…) to comprehend the output in C.
In Java, x=x++
, is evaluated as:
int temp = x;
x = x + 1;
x = temp;
So, basically there is no change is x
after that expression.
In C
however, that expression is an Undefined Behaviour. Also see Sequence Points Wiki
This code cause undefined behaviour in C so the result may be any, 7, 8, 15 or Page fault. Why this code give 7, is compiler matter.
In the Java background, something like the following occurs (for the i = i++
statement):
int temp = i; // store current value of i
i = i + 1; // increase i because of i++
i = temp; // assign to i
x=x++;
This gives arbitrary results in C, mainly depending on compiler. Read about sequential points
in C. You may refer to C Programming
by Dennis ritchie
.
it is because of operator precedence. = has more precedence in C than Java.