How do I write a short literal in C++?

Kip picture Kip · Oct 16, 2008 · Viewed 53.3k times · Source

Very basic question: how do I write a short literal in C++?

I know the following:

  • 2 is an int
  • 2U is an unsigned int
  • 2L is a long
  • 2LL is a long long
  • 2.0f is a float
  • 2.0 is a double
  • '\2' is a char.

But how would I write a short literal? I tried 2S but that gives a compiler warning.

Answer

Mike F picture Mike F · Oct 16, 2008
((short)2)

Yeah, it's not strictly a short literal, more of a casted-int, but the behaviour is the same and I think there isn't a direct way of doing it.

That's what I've been doing because I couldn't find anything about it. I would guess that the compiler would be smart enough to compile this as if it's a short literal (i.e. it wouldn't actually allocate an int and then cast it every time).

The following illustrates how much you should worry about this:

a = 2L;
b = 2.0;
c = (short)2;
d = '\2';

Compile -> disassemble ->

movl    $2, _a
movl    $2, _b
movl    $2, _c
movl    $2, _d