-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
  • 3,739
  • 2
  • 40
  • 45
D0nK3Y_D0nK
  • 63
  • 1
  • 3
  • 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

2 Answers2

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
  • 127,356
  • 13
  • 118
  • 231
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