1,120 views
2 votes
2 votes
#include<stdio.h>

int main() {
   int y=3 ;

int z= (--y) + (y=10);

printf("%d  ",z);
}
 

can someone explain how is it 20 ?

1 Answer

Best answer
5 votes
5 votes

It's clearly mentioned in C Book by Kerninghan And Ritchie  :

The operands of a binary operator may be evaluated in any order ; it is not specified..

Hence for the given question , the program will show undefined behaviour and answer will be compiler dependent..This is because of following 2 possible scenarios :

Case 1 :

Left operand evaluation followed by right one : If we do so , y is decremented first using predecrement operator , so y now becomes 2..So left operand value = 2..Then in the right part , the assignment "y = 10" is done so right operand value is 10..Hence z = left operand + right operand  =  2 + 10  =  12

Case 2 :

Now if we consider right one being evaluated first , so y becomes 10 first and hence right operand = 10..Then on predecrement y becomes 9 first and then the value is used for left operand..

So z here  = 10 + 9  =  19..

Hence in no case u will get 20..Had it been a post decrement operator then , yes the value would have been 13 for case 1 and 20 for case 2..

In short , the given question shows undefined behaviour..

selected by

Related questions

4 votes
4 votes
1 answer
2
ritwik_07 asked Jun 10, 2023
460 views
#include<stdio.h #include<string.h #define MAX(x, y) ((x) (y) ? (x) : (y)) int main() { int i = 10, j = 5, k = 0; k = MAX(i++, ++j); printf("%d %d %d", i, j, k); return ...
0 votes
0 votes
1 answer
3