Question:
C-Program operator Numerical?
Jack
2018-02-13 06:43:32 UTC
int a=2,b=3,c;
a=(b++)+(++b)+a;
c=a>b?a:b;
b=(a++)+(b--)+a;
c=c++*b--
Find the final values of a,b and c.
Four answers:
husoski
2018-02-13 11:44:14 UTC
The second line has "unspecified behavior" (UB). C doesn't define what order most the operands of most operators are evaluated, so the values added in "(b++) + (++b)" could be different on different C compilers; or even on the same compiler when compiled in a different context such as when compiled for debugging or with different optimization options. The left operand could be 3 or 4 and the right could be 4 or 5, so sums from 3+4+2 to 4+5+2 are possible.



In any case, it seems a be greater than b, so c will get the unspecified value of a in the next statement.



Then in the fourth statement, b now gets an unspecified value based on a.



So, the final values of a, b and c are all unspecified.



In general, modifying a variable (with ++, -- or an assignment operator) and then using that variable again in the same expression leads to problems like this one. Only the ||, &&, ?: and comma operators define the order that their operands are evaluated in.
?
2018-02-13 22:13:27 UTC
You have undefined behaviour

in this line

a=(b++)+(++b)+a;

you are modifying b twice between sequence points -- not good.

and in this line

b=(a++)+(b--)+a; // you are accessing a other than to determine its new value and modifying b twice between sequence points



c=c++*b-- // oops modifying c twice between sequence points
2018-02-13 14:35:04 UTC
What happened when you tried the examples for yourself?



The results will vary depending the compiler in use, since at least one of the statements is "unspecified".
?
2018-02-13 12:01:12 UTC
It can vary with different compilers. My compiler returned 11, 25 and 260 respectively once I added the missing ';' character at the end of the last line.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...