Search code examples
cbooleanoperator-precedence

Printing a Boolean result in C


I read that

int c;
while(c = getchar() != EOF)
{
    putchar(c);
}

will print the value 0 or 1 depending on whether the next character is an EOF or not. Because != has a higher precedence than =.

But when I run this program in GCC, I get a character that looks like

|0 0|
|0 1|

as output when I press Enter.


Solution

  • putchar prints a character. By printing the values 0 and 1, you're printing the null and start of heading (SOH) characters, both control characters. You'll need to convert the numbers 0 and 1 to something that's printable, either by calculating a printable value directly from the 0 or 1:

    while (...) {
        // note: the C standard (§ 5.2.1-3 of C99) ensures '0'+1 is '1', which is printable
        putchar(c+'0');
    }
    

    or using c to decide what to print.

    while (...) {
        if (c) {
            ...
        } else {
            ...
        }
        // or:
        //putchar(c ? ... : ...);
        // though feelings on the ternary operator vary.
    }