Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is 0XAA an unsigned int and not an int?

Tags:

c

I saw this from C Primer Plus, the 6th edition, Review Questions in Chapter 3.

The question:

Question Picture

Answer in Appendix A:

Answer Picture

Notice d.0XAA, my answer is int constant, hexadecimal format, But the answer is unsigned int

and I wonder why

like image 728
Morris Li Avatar asked Nov 18 '16 12:11

Morris Li


1 Answers

That book is incorrect. As per C11 6.4.4.1, the type of integer constants of hexadecimal are determined from this table:

Suffix    ...    Octal or Hexadecimal Constant

None      ...    int
                 unsigned int
                 long int
                 unsigned long int
                 long long int
                 unsigned long long int

u or U    ...    unsigned int
                 unsigned long int
                 unsigned long long int

Your constant 0xAA has no suffix so the top part of the above table is what applies. Meaning: the compiler will first check if the value can fit in an int. If it doesn't fit, it will check if it will fit in an unsigned int and so on.

On any known implementation of C, the value 0xAA will certainly fit inside an int. The correct answer to the question is int.

However, had the constant been 0xAAu, the bottom part of the cited table would have applied and the result would have been an unsigned int.

like image 55
Lundin Avatar answered Oct 19 '22 22:10

Lundin