Krishna said:
I missed one of the parenthesis in the following code and got the
following result, I am not able to figure it out can any one explain.
Thanks
mian(void){
int c;
while(c=getchar()!=EOF)
putchar(c);
}
Result: (Entered 1)
1
That's not your actual code. If it were, it wouldn't have compiled
because you mispelled "main", and you would never have gotten
any output. Please copy-and-paste the exact code you compiled;
don't try to re-type it.
Here's a corrected version of your program. I've added a pair of
parentheses; they don't change the semantics, but they do help
clarify what's going on. I've also added "#include <stdio.h>";
even though you might get away with omitting it, it's not optional.
#include <stdio.h>
int main(void) {
int c;
while (c = (getchar() != EOF)) {
putchar(c);
}
return 0;
}
The condition on the while loop evaluates the subexpression
(getchar() != EOF) and assigns the result to c. The "!=" operator
yields 1 if its operands are unequal, 0 if they're equal. If you
enter the character '1', getchar() will return the value of '1'
converted to int (probably 49) which clearly is not equal to EOF
(typically -1). So c gets the value 1, which is then passed to
putchar().
The loop terminates when the condition is false (0), which happens
when getchar() returns EOF, i.e., when it reaches end-of-file.
So, just by luck, the termination condition happens to be correct.
On most systems, the character value 1 is control-A, a non-printable
control character. Your program is printing that character
once for each input character it sees, but you're not seeing it.
(You're seeing the '1' you typed because your terminal echoes it.)
The final 0 value assigned to c is not displayed because the loop
terminates at that point.
Depending on your system, you may be able to see the non-printable
characters. On Unix-like systems, for example, you can use "cat -A":
% gcc c.c -o c
% ./c | cat -A
1234
^A^A^A^A^A%
%
The real solution, as I'm sure you know, is to fix the code.