Question

This is an ugly code used only to terrorize job applicants during interviews... But I cannot understand the logic behind it. Can someone explain why the expression with "b" is not equal to the one with "a"?

#include <stdio.h>
void main(){
    int a = 1, b = 1, c = 1;
    printf("%d %d %d", ++a + a++ + 1, 1 + ++b + b++, ++c + c++); // displays 6 5 5
}

Thank you very much.

Was it helpful?

Solution

Read up on Undefined behavior and sequence points.

This is a slightly different, yet similar example (thanks Zan):

2) Furthermore, the prior value shall be accessed only to determine the value to be stored.

C++ example:

std::printf("%d %d", i,++i); // invokes Undefined Behaviour because of Rule no 2

OTHER TIPS

The logic is simple:

Create Undefined Behavior and let the nasal demons terrorise the job applicant. That is known as job security.

If you write to a variable, you must not access it again without intervening sequence point except to calculate the value which shall be written.

There's a second case of UB or at least Implementation Defined Behavior:

void main()

Should be one of

int main(void)
int main(int argc, char* argv[])

Just to prove that this is a terrible idea, here's the output in VS2012 (technically C++ compiler I suppose):

5 5 4

GCC & G++:

6 5 5

So apparently your interviewer tried it in GCC.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top