Reputation: 43
Why doesn't gcc give any warnings about this code?
#include <stdio.h>
void printDigits(int *arr, int arrsize);
int main() {
int number[] = { 1, 7, 8, 3, 6, 5, 4, 2 };
size_t arraysize = (sizeof(number) / sizeof(number[0]));
printDigits(number, arraysize);
return 0;
}
void printDigits(int *arr, int arrsize) {
int i;
for (i=0; i<arrsize, i++;) {
printf("%d ", arr[i]);
}
}
Specifically about the for loop in printDigits function. It's:
for(i=0; i<arrsize, i++;)
while it really should be for(i=0; i<arrsize; i++)
Gcc didn't give me any warnings and it took me a while to figure out why doesn't the array print out.
Upvotes: 4
Views: 154
Reputation: 67780
It is a valid C. This for loop will execute until i
is non zero
Upvotes: -2
Reputation: 311068
This for loop
for(i=0; i<arrsize, i++;){
printf("%d ", arr[i]);
}
is a valid C construction. In the condition of the loop there is used the comma operator
i<arrsize, i++
the value of which is the value of its second operand. So the body of the loop will not be executed because the value of the expression i++
is 0 (that is value of the variable i
before its increment).
From the C Standard (6.5.17 Comma operator)
2 The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value
Pay attention to that any expression in the for loop may be omitted. For example you can even write like
for ( ; ; )
{
//...
}
Also you should at least change the type of the second function parameter from int
to size_t
because you are passing an argument of the type size_t
.
The function should be declared like
void printDigits( const int *arr, size_t arrsize );
Upvotes: 3
Reputation: 40891
There is a warning. i<arrsize
is computed but then discarded, so gcc warns:
warning: left-hand operand of comma expression has no effect [-Wunused-value]
(Which is enabled by -Wall
)
Upvotes: 7