Search code examples
cwhile-loopconditional-statementsconditional-formattingdo-while

Can't you use `,` operator to define a variable in a while loop's expression in C?


Why can't we define a variable in while loop's condition expression in the same way as we can define in a for loop?

For example:

#include <stdio.h>


int main() {
    while((int c = getchar()) != EOF) 
         printf("%c", c);
    
    return 0;
}

Chat GPT 4.0 and Perplexity.ai had suggested me the above piece of code. But apparently that's not allowed; I found out that through trail and error. I also tried using , operator too.

Example:

#include <stdio.h>

int main() {
    while((int c = getchar(), c != EOF) 
         printf("%c", c);
    
    return 0;
}

As the value of the conditional test is only going to be the right most expression (c != EOF) because , operator was used. But even then the compiler didn't compile it. So, how can we define a variable in the while loop's conditional expression?


Solution

  • A while-loop (6.8.5.1) expects a controlling expression (6.5) but int c = getchar() is a declaration with an initializer (6.7). In C a declaration is not an expression. You can use the comma operator in the controlling expression along these lines:

    #include <stdio.h>
    
    int main() {
        { // scope of the variable c
            int c;
            while(c = getchar(), c != EOF)
                printf("%c", c);
        }
    }
    

    The first part of a for-loop is a clause which permits declarations (6.8.5.3) and you declare multiple variables of the same type by comma separating them:

    for(int c, y, a; ...)
    

    In my opinion, assignment in the controlling expression is harder to read, so I favor simpler constructs like:

    #include <stdio.h>
    
    int main() {
        for(;;) {
            int c = getchar();
            if(c == EOF) break;
            printf("%c", c);
        }
    }