carl.hiass
carl.hiass

Reputation: 1774

Literal for short or char (integers)

Is there a literal syntax to write a char or short? For example:

Or, do you need to cast it to do the literal notation, for example:

Note: even if I write it as 'a', it still recognizes it as an int (at least when I inspect it in VS Code).

Upvotes: 6

Views: 617

Answers (2)

Petr Skocik
Petr Skocik

Reputation: 60068

There are no suffixes for short types (types narrower than int) and you don't need them.

Outside of preprocessor conditionals, the suffixes can be fully expressed in terms of casts or more generically casts and the ternary operator ( 0xfffffffffU isn't equal to (unsigned)0xfffffffff, but it is equal to (1?0xfffffffff:0u) on platforms with 32-bit unsigneds).

In preprocessor conditionals, casts won't work, so you do need at least the U suffix there if you need unsigned semantics. The other suffixes, I guess, are just for convenience for when a macro needs to be used in both C and in preprocessor conditionals, although things like ((type)+42) can also be employed in such situations (relying on keywords expanding to 0 in preprocessor conditionals).

As Eric Pospitschil has pointed out, preprocessor arithmetic is done in intmax_t/uintmax_t so you don't need to widen the constants as you would in C proper to prevent some instances of undefined behavior.

Upvotes: 3

dbush
dbush

Reputation: 223917

There is no suffix to specify integer literals of a type smaller than int like you can with larger types. The closest you can come to that would be to use a compound literal:

(char){4}
(short){4}

Even so, using such a construct wouldn't do much because in most contexts an integer type smaller than int would be promoted to int when used in an expression.

From section 6.3.1.1p2 of the C standard regarding integer conversions:

The following may be used in an expression wherever an int or unsigned int may be used:

  • An object or expression with an integer type (other than int or unsigned int) whose integer conversion rank is less than or equal to the rank of int and unsigned int.
  • A bit-field of type _Bool, int , signed int, or unsigned int.

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.

Upvotes: 1

Related Questions