MuYuan Li MuYuan Li - 1 year ago 105
C Question

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

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

constant, hexadecimal format, But the answer is
unsigned int

and I wonder why

Answer Source

That book is incorrect. As per C11, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download