Bloomberg LP Interview Question
Financial Software DevelopersCountry: United States
Interview Type: In-Person
I'm a java guy but here goes. Since there are no braces to identify the block of code in the for loop, the count = count++; statement is the only statement part of the for loop. So count goes from 1 (count being initially o, count++ is 1) to 10 (the last value for count is 9, so count++ is 10) The output of the code is 10.
int count = 0;
40117e: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp)
401185: 00
int res = 0;
401186: c7 44 24 08 00 00 00 movl $0x0,0x8(%esp)
40118d: 00
res = count++;
40118e: 8b 44 24 0c mov 0xc(%esp),%eax
401192: 89 44 24 08 mov %eax,0x8(%esp)
401196: 83 44 24 0c 01 addl $0x1,0xc(%esp)
res = ++count;
40119b: 83 44 24 0c 01 addl $0x1,0xc(%esp)
4011a0: 8b 44 24 0c mov 0xc(%esp),%eax
4011a4: 89 44 24 08 mov %eax,0x8(%esp)
count = count++;
4011a8: 83 44 24 0c 01 addl $0x1,0xc(%esp)
count = ++count;
4011ad: 83 44 24 0c 01 addl $0x1,0xc(%esp)
My friend and I did some research about this question with asm. We found for res = count++, the asm does that:
temp = count;
res = count;
count = count +1;
if we say count = count ++, compiler will optimize this 3 one line into one count = count +1;
I think the tricky reason that confuses ppl comes from how we implement operator ++(int) overload for class. We would copy the object, increase the object, then return the old obj for return and assignment. But for primary type, compiler copy, assign and then increase. That's a good question to understand the primary type's difference from the operator overload for class.
I compiled both
count=count++
and
count =++count
with gcc version 4.1.2 both result the same output as 10.
case( I )
#include <iostream>
using namespace std;
void main()
{
int count = 0;
for(int i=0; i < 10; ++i){
count = count++;
}
cout<<"Output of this code is: "<<endl;
std::cout << count <<endl;
}
root [0] .L main.C
root [1] main()
Output of this code is:
0
case ( II )
#include <iostream>
using namespace std;
void main()
{
int count = 0;
for(int i=0; i < 10; ++i){
count = ++count;
}
cout<<"Output of this code is: "<<endl;
std::cout << count <<endl;
}
root [0] .L main.C
root [1] main()
Output of this code is:
10
The behaviour of this type of self-assignment is undefined and dependent on the compiler implementation. So, the result may be either 0, or 10, or even a not-compilable code. The undefined behaviour happens due to missing sequence point in the evaluation of expression "count = count++;"
- ashot madatyan May 25, 2012You can read it @en.cppreference.com/w/cpp/language/eval_order