-1

I want to assign the ARRAY_SIZE(X) to an int. are there any risk to get garbage value in the int since ARRAY_SIZE(X) is an unsigned long

#define ARRAY_SIZE(X) (sizeof((X))/sizeof((X)[0]))
int m = ARRAY_SIZE(X)

are there a risk to get garbage value in m?

MOHAMED
  • 41,599
  • 58
  • 163
  • 268

2 Answers2

2

You shouldn't get garbage (as in completely unpredictable) values.

Narrowing conversions to signed types when the value won't fit in the target type will either be implementation-defined or they'll raise a signal (6.3.1.3p3).

If they don't raise a signal, you can verify absence of information loss by checking the values and signs of the source and destination are the same.

(If you store into unsigneds, the conversion will always be well defined, and you'll only need to compare the values (no signs in unsigned types) to verify absence of information loss.)

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
-1

If the value in ARRAY_SIZE(x) is bigger than what can fit in an int, you can't help but get garbage.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101