C++ Convertion Char Int Arm

I have this very simple C++ code :

#include <iostream>
int main() {
    std::cout << (int)(char)(int)char(-2);
    return 0;
}

I am executing it on different setups :

  • Ubuntu 20.04 x64 (g++) -> Output : -2
  • Windows 10 x64 MSVC 2017 -> Output : -2
  • MacOS x64 Clang -> Output -2
  • Ubuntu Armv8 (g++) / EC2 Instance -> Output : 254

I want to obtain -2 all the time, and I don't understand this difference in behavior.

Does anyone have any idea?

2

3 Answers

A compiler is allowed to choose if char is signed or unsigned. The standard says that they have to pick, but don't mandate which way they choose.

GCC supports -fsigned-char and -funsigned-char to force this behavior.

3

From the ISO C++ International Standard (Tip of trunk):

ยง6.8.2 Fundamental Types

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.