Dover Organization Interview Question
Developer Program EngineersCountry: India
Interview Type: In-Person
int x, y;
x = 5; y = 6;
x = y++ + x++; // x is 12 (5+6 = 11 and then x is incremented to 12 and y to 7)
// y = 7 now and x =12
y = ++y + ++x;// 8 + 13
// x = 12, y = 20
warning: operation on ‘x’ may be undefined
warning: operation on ‘y’ may be undefined
Why do they ask such questions.
I agree that it's very dumb of companies to ask stuff like this. No sane person programs using these sorts of constructs anyway, so if you don't know this kind of stuff, to me that would say good things about you.
I was asked a similar question during a phone interview.
According to the C standard, you are not supposed to modify a value more than one time between sequence points:
"Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored."
Each of the assignment statements above falls within a single set of sequence point boundaries. (There is a sequence point at the beginning of the assignment statement and one at the end of the assignment statement, and none in between.) So, according to the standard, this is not a legal C or C++ program.
At least with gcc v4.6.1, the following code generates two different numbers depending on whether the optimizer is enabled:
int x, zero;
zero = 0;
x = 5;
printf("(zero + ++x) * (zero + --x): %d\n", (zero + ++x) * (zero + --x));
The output of first program is undefined. There is no sequence defined in the statement:
x = y++ + x++;
y = ++y + ++x;
In the older version compilers, the output is 13.......21, but the newer version compilers(c-99 onwards) define the behavior as undefined.You will get the error.
See here: ideone.com/mEqiP
If the value of the same variable is changed more than once, then it is called as UB(undefined behavior).
For more details, search sequence point on wiki.
1. x=13,y=21;
- Neetesh Bhardwaj April 27, 20123. **p points the value at the address which is stored at address p and &(*p) points address p