-3
for ( i= 0; i < sizeof(r)/sizeof(r[0]); ++i ){ 
        r[i]= 0; 
}

So this is the for loop I'm having troubles with, how can I rewrite it so I don't get the warning:

comparison between signed and unsigned integer expressions [-Wsign-compare]
chrk
  • 4,037
  • 2
  • 39
  • 47
D0nK3Y_D0nK
  • 63
  • 1
  • 4
  • 8
  • 3
    `int size = sizeof(r)/sizeof(r[0]);` ... `i < size` or `size_t i;` – BLUEPIXY Aug 17 '14 at 02:45
  • Possible duplicate of [C: how can I fix warnings like: "comparison between signed and unsigned"](http://stackoverflow.com/questions/859943/c-how-can-i-fix-warnings-like-comparison-between-signed-and-unsigned) – phuclv Mar 24 '17 at 13:31

3 Answers3

6

sizeof() returns an unsigned integer of type size_t. So use an index of the same type.

size_t i;
for (i = 0; i < sizeof(r)/sizeof(r[0]); ++i) { 
  r[i] = 0; 
}

Recommend to not use int size = sizeof(r)/sizeof(r[0]);. The range of size_t may greatly exceed the positive range of int. The assignment could then lose significant bits.

size_t is the type best used to index array variables. Remember, though, since it is some unsigned integer, it can not represent negative indexes.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
2

In your code:

for ( i= 0; i < sizeof(r)/sizeof(r[0]); ++i ){ 
        r[i]= 0; 
}

I think the "i" is declared as an int, try "unsigned int i;" like this:

for (unsigned int i = 0; i < sizeof(r)/sizeof(r[0]); ++i ){ 
        r[i]= 0; 
}

Run your code and it should remove this warning for sure.

Amession
  • 249
  • 1
  • 10
0

The warning can be suppressed by typecasting the sizeof operator's output using (int).

for ( i= 0; i < (int)(sizeof(r)/sizeof(r[0])); ++i )
{ 
        r[i]= 0; 
}

However, the range of size_t (the result type of sizeof) is often much higher than int, so the result of the cast can become negative for large objects. Only use this technique if you are sure the result will fit in a signed integer.

Josh Klodnicki
  • 585
  • 6
  • 18