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]
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]
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.
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.
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.