0

I would like to initialize a short to a hexadecimal value, but my compiler gives me truncation warnings. Clearly it thinks I am trying to set the short to a positive value.

short my_value = 0xF00D; // Compiler sees "my_value = 61453"

How would you avoid this warning? I could just use a negative value,

short my_value = -4083; // In 2's complement this is 0xF00D

but in my code it is much more understandable to use hexadecimal.

sourcenouveau
  • 29,356
  • 35
  • 146
  • 243

2 Answers2

3

Cast the constant.

short my_value = (short)0xF00D;

EDIT: Initial explanation made sense in my head, but on further reflection was kind of wrong. Still, this should suppress the warning and give you what you expect.

Donnie
  • 45,732
  • 10
  • 64
  • 86
  • I am using C++ so I tried a static_cast, but I still get the warning. Maybe I'm supposed to use reinterpret_cast? – sourcenouveau Nov 18 '10 at 20:24
  • Using a C-style cast got rid of the warning, thank you. Now I need to read up on why there isn't a C++-style cast to handle this scenario. – sourcenouveau Nov 18 '10 at 20:27
  • 1
    You could `short(0xF00D)`, which is a little more C++-style. The problem is that there isn't an integer literal to specify a `short int` like there is for a `long`. – Travis Gockel Nov 18 '10 at 20:33
0

You are assigning an int value that can not fit short, hence the warning. You could silent the compiler by using a c-type cast, but it is usually a bad practice.

A better way is not to do that, and to assign a negative value. Or, if the hexadecimal value makes more sense, to switch to unsigned short.

BЈовић
  • 62,405
  • 41
  • 173
  • 273