Printf not printing out the expected result, why?

113 views Asked by At

I am programming in c on ubuntu terminal gcc compiler. printf is not giving any output. Please explain why.

#include <stdio.h>
int main()
{
    int c;
    while (c = getchar() == EOF)
    {
        printf("%d\n", (int)c);
    }
    return 0;
}
2

There are 2 answers

1
alinsoar On
 c = getchar() == EOF

means c = (getchar() == EOF) as the assignment expression is right-associative and has the lowest priority from all the expressions apart from comma-expression.

which means for your code, c = 0 almost all the time. So the loop while(0) is not executed.

You mean while ((c = getchar()) != EOF).

Also, it is no need to cast c to int in

 printf("%d\n", (int)c);

because the default argument promotions do it automatically.

The correct code may be so:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF)
        printf("%d\n", c);
    return 0;
}
0
Sourav Ghosh On

To ammend the other answer, see the operator precedence table.

The equality operator == has higher precedence over the assignment =, so in your case, first the equality check will take place and then the result will get assigned, which is what you don't want. So, a statement like

  (c = getchar() == EOF)

gets grouped like

  ( c = (getchar() == EOF) )

which is wrong.

Printf not printing out the expected result, why?

To elaborate the no output part, in your case, the result of the comparison is either a 0 or 1. Related, quoting C11, chapter ยง6.5.9

[...] Each of the operators yields 1 if the specified relation is true and 0 if it is false. The result has type int. [...]

So, the assigned value is either 0 or 1, and you try to print it using %c format specifier. This value(s) does not have a printable representation, thus you don't see any output.

FWIW, here's a list of printable and non-printable values.

Solution: Make it explicit, using a pair of parenthesis to enforce the order of execution of the sub-expressions, like

 while ( (c = getchar()) != EOF )

That said,

  • The conforming signature of main() is int main(void), at at least in a hosted enviroment.

  • The cast to (int) is superfluous, (if in lesser rank than int) the supplied argument is implicitly promoted, anyway.