Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Test - Does sign bit 1 always mean negative?

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

like image 867
Armen Tsirunyan Avatar asked Mar 24 '13 10:03

Armen Tsirunyan


People also ask

How do I change the sign of a bit?

The best and most portable way to change the sign bit is simply a = -a .

How many bytes is an unsigned long?

Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).

How many bits is an int C++?

int is always 32 bits wide. sizeof(T) represents the number of 8-bit bytes (octets) needed to store a variable of type T .


1 Answers

I would say it is undefined (and not implementation-defined) for a different reason.

From 5.8:3

The value of E1 << E2 is E1 left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 × 2E2 , reduced modulo one more than the maximum value representable in the result type. Otherwise, if E1 has a signed type and non-negative value, and E1 × 2E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.

like image 97
jalf Avatar answered Oct 12 '22 05:10

jalf