I was just taking a C++ test and I got the following question wrong:
Q: What is the output of the following program?
#include <iostream>
#include <stdint.h>
using namespace std;
int main() {
int a = 0;
for (int8_t i = 1; i > 0; i <<= 1)
a++;
cout << a;
return 0;
}
There were the following answers to choose from
- 8
- 7
- Undefined Behavior
- Compile Error
The "correct" answer was 7. If there was "Implementation-Defined Behavior" in the answers, I would choose that, so I chose Undefined Behavior which was sort of the closest. I understand that in sign-and-magnitute, 1's complement, and 2's complement the answer will be 7. But doesn't the C++ standard theoretically allow any other number representations? For example, sign and magnitude, but 0 means negative?
Am I correct in that the real correct answer to this question should be Implementation-Defined Behavior, and if not, could you please explain why the answer is 7 regardless of the implementation?
I read the comments to the question and it appears that initially the type of a
was char, which apparently had raised a lot of complaints about whether char
is signed or not, so the testsetter changed it to int8_t. As a bonus question, is <stdint.h>
part of C++? O_O