3

I have compiled and executed this code on macOS in Xcode 10.0 (clang: Apple LLVM version 10.0.0) and it's returning 255. On the other hand, on Windows in Visual Studio Community Edition v.15.8.6 it's returning -1. Can someone explain this behaviour on macOS? Code listed below.

int main() {
    return -1;
}
hellow
  • 12,430
  • 7
  • 56
  • 79
Peter
  • 435
  • 1
  • 3
  • 11

3 Answers3

7

On POSIX systems (like macOS or Linux) the return-code from a process is made up of several parts, and the return-code from main is only stored in the low eight bits of the int value.

Most modern systems uses two's complement to represent negative integers, and with that the signed value -1 becomes 255 because all bits in the byte will be set.

Because of this it's not recommended that you return negative numbers from main (or call exit with a negative number). Instead use only small non-negative numbers, where 0 is considered success. Or of course use the standard EXIT_SUCCESS and EXIT_FAILURE macros.


Windows, not being a POSIX systems, doesn't really care about this, and uses the whole int value for the returned value.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

Certain OSs (POSIX) have return code range limit from 0 to 255 (effectively a uint8_t). -1 converted to uint8_t is 255.

Kon
  • 4,023
  • 4
  • 24
  • 38
1

Depending on the OS the error code returned to the parent process is a char, int8_t, uint8_t or possibly anything else. From the numbers you get MacOS seems to have uint8_t so a -1 shows up as 255 while Windows has an int8_t or larger so -1 is reported.

This has nothing to do with your program but with the datatype used in the OS to report return codes of processes. Nothing you can change there.

Note: You should not use -1/255 as exit code as that is already used to signal an error loading your program on unix/linux system. It's best to stick with 1,2,3,... as error codes to avoid conflicts.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42