Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Literal for short or char (integers)

Tags:

c

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

  • 4 --> int
  • 4L --> long
  • 4LL --> long long
  • 4C ?
  • 4H ?

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

  • (char) 4 --> char
  • (short) 4 --> short

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

like image 596
carl.hiass Avatar asked Oct 14 '22 22:10

carl.hiass


1 Answers

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.

like image 101
PSkocik Avatar answered Nov 13 '22 00:11

PSkocik