Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 377
narek Avatar asked Jan 24 '23 12:01

narek


1 Answers

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)

like image 60
Artyer Avatar answered Apr 06 '23 11:04

Artyer