0

I learned that in C language main() typically return(s) an int. I have tested it so far. For instance, int is 4 bytes, But the shell only accepts an unsigned char being returned from main(). On my systems (Linux, FreeBSD and NetBSD), it is likely that the shell (bash and tcsh) only accept the only one rightmost byte. For example if main() return 0xabcdef0a, after compile and run in shell then issue the command echo $?, the results are always 10 (0x0a) in all systems. So my question, why doesn't main() return an unsigned char instead of an int?

Chung Lim
  • 169
  • 1
  • 1
  • 10
  • 9
    History — there weren't any `unsigned char` in C when the convention was established. Also, the process that traps the exit status gets a 16-bit value, 8 bits of which are the exit status and 8 bits of which are signal-related information (0 in the case that the child didn't die from a signal). And in the days when this was established, `int` was usually 16 bits, so `int` was appropriate. – Jonathan Leffler Apr 10 '17 at 18:18
  • @JonathanLeffler Thank you for your clarification. It makes me clear. :-) – Chung Lim Apr 10 '17 at 18:34
  • What would be the work around in order to make this to work? – Nguai al Apr 10 '17 at 18:36
  • @Nguaial, ..."work"? Everything is already working precisely as POSIX defines it. – Charles Duffy Apr 10 '17 at 18:47
  • 1
    From the POSIX specification, emphasis added: "When reporting the exit status with the special parameter '?', the shell shall report **the full eight bits of exit status available**". Thus, a shell isn't expected to have more than 8 bits of content represented in `$?`. – Charles Duffy Apr 10 '17 at 18:52

1 Answers1

2

Converting comment into an answer.

The reason is a common one: History. There wasn't an unsigned char type in C when the convention was established in the early 1970s. Also, the process that traps the exit status gets a 16-bit value, 8 bits of which are the exit status and 8 bits of which are signal-related information (0 in the case that the child didn't die from a signal). And in the days when this was established, int was usually 16 bits, so using int was appropriate.

You could also look at ExitCodes greater than 255 — possible?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • And the old MS-DOS `errorlevel` used in batch files to take action on a program's exit value, has a maximum value of 255 (8 bits). – Weather Vane Apr 10 '17 at 19:06