1

I have two variables:

int a;
uint b;

I also have an array:

float c[100];

If I want to pass a+b as the index of array c such that:

c[a+b] = 10.0;

For safety purpose, we should make sure a+b returns uint. Does it return unit?

Should I force its return value to be an uint?

alk
  • 69,737
  • 10
  • 105
  • 255
HeyMan
  • 163
  • 2
  • 11
  • What is `uint`? There is no such standard type in C. Is it a typedef for `unsigned int`? – Keith Thompson Jan 25 '15 at 06:54
  • Related: http://stackoverflow.com/q/10047614/694576 – alk Jan 25 '15 at 10:03
  • possible duplicate of [Unsigned and signed values in C (what is the output)](http://stackoverflow.com/questions/3668734/unsigned-and-signed-values-in-c-what-is-the-output) – phuclv Jan 25 '15 at 12:31

1 Answers1

2

Yes, when you add an int and an unsigned int, the int value gets promoted to unsigned int, so you'll be fine. Be careful that a isn't negative, however, or you'll be in for a nasty surprise!

BlackJack
  • 2,826
  • 1
  • 22
  • 25
  • Thanks for your reply. What it a is negative? How can it be promoted to unsigned int? – HeyMan Jan 25 '15 at 05:17
  • @UKYECE Technically that should be a new question - "What happens if I cast a negative value to `unsigned int`?" – user253751 Jan 25 '15 at 06:02
  • 1
    @immibis technically it should be "What happens when a negative `int` is converted to `unsigned int`?". A cast requires a cast operator. – M.M Jan 25 '15 at 09:42
  • 1
    It's not particularly nasty: the negative int gets `UINT_MAX+1` added to it, to make it a positive `unsigned int` . `-1 + 5u` gives `4u` . – M.M Jan 25 '15 at 09:42
  • is that "assuming 2s complement", or is it a standards guarantee? – sp2danny Jan 25 '15 at 13:04
  • @sp2danny it's a standards guarantee. – M.M Jan 25 '15 at 14:05
  • @sp2danny: If N is positive, adding -N to, or subtracting N from, an unsigned integer value will yield the number which, when added to N, would yield the original. The fact that (unsigned)-1 is UINT_MAX has nothing to do with twos-complement notation and everything to do with the fact that (UINT_MAX+1)==0u. – supercat Mar 30 '15 at 15:22