Unexpected unsigned integer behavior

前端 未结 2 1206
后悔当初
后悔当初 2021-01-16 05:22

I encountered this unexpected output with the following code in which I was verifying the maximum values (represented in decimal form) of the unsigned forms of short and int

相关标签:
2条回答
  • 2021-01-16 05:44

    Using printf(), your conversions in the format string must match the type of the arguments, otherwise the behavior is undefined. %d is for int.

    Try this for the maximum values:

    #include <stdio.h>
    
    int main()
    {
        printf("Max unsigned int = %u\n", (unsigned)-1);
        printf("Max unsigned short = %hu\n", (unsigned short)-1);
        return 0;
    }
    

    Side notes:

    • the maximum value of any unsigned type is -1 cast to that type.
    • Put newline at the end of your lines. Among other reasons, this flushes stdouts buffer with the default setting of line buffered.
    0 讨论(0)
  • 2021-01-16 05:44

    You need to use %u for the format specifier for an unsigned type.

    0 讨论(0)
提交回复
热议问题