Any benefit in using WEXITSTATUS macro in C over division by 256 on exit() status?

后端 未结 4 942
清酒与你
清酒与你 2020-12-03 05:48

I was doing an exercise for university where I had to return a value with exit, that value was actually a count of something. This could be above 255 (which exit() can\'t ha

4条回答
  •  暖寄归人
    2020-12-03 06:13

    If the status variable is a signed 16-bit integer (a 'short') on a machine where 'int' is a 32-bit quantity, and if the exit status is in the range 128..255, then WEXITSTATUS() still gives you a correct value where dividing by 256 or simply shifting right will give you an incorrect value.

    This is because the short will be sign extended to 32-bits, and the masking undoes the the sign extension, leaving the correct (positive) value in the result.

    If the machine used 16-bit integers, then the code in WEXITSTATUS() would probably do shift then mask to ensure similar behaviour:

    #define WEXITSTATUS(status) (((status)>>8) & 0xFF)
    

    It is because the implementation takes care of such details for you that you should use the WEXITSTATUS() macro.

提交回复
热议问题