Search code examples
c

Why No Variable Declarations in Boolean Expressions in C?


I am studying C programming from K&R, and while experimenting with the example programs, I came across this code snippet:

#include <stdio.h>
int main(){                                                               
    int c;
    while((c = getchar()) != EOF){
        putchar(c);
    }
    return 0;
}

and made a slight modification:

#include <stdio.h>
int main(){
    while((int c = getchar()) != EOF){
        putchar(c);
    }
    return 0;
}

I expected the getchar() function to be executed first, returning an int value that would be stored in the integer variable c, and subsequently, the c != EOF expression would be evaluated. However, it appears that this is not the case. Can someone explain why that's not how it works?


Solution

  • In C, declarations are for informing the compiler about what an identifier (a name) means. They specify that a name is a variable of a certain type or is a name for a type or is a tag for a structure, and so on.

    Expressions are for specifying the computation of a value.

    They are separate things. Declarations are not subparts of expressions. You cannot use a declaration in the test condition of an if statement.

    (There are limited opportunities to use “type names” in expressions, such as in the operand of a sizeof expression, and these type names may declare structures, unions, enumerations, and their members. These are not full declarations and cannot declare variables.)