Search code examples
cfor-loopcompiler-warningscomma-operator

No compiler warning when there's a comma instead of a semicolon in a for loop


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.


Solution

  • 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)