need help understanding a C program

Special K

Diamond Member
Jun 18, 2000
7,098
0
76
I am reading SAMS "Learn C in 21 days" and have come upon an example program that I do not quite understand. It's pretty short, and I was wondering if someone could help me out with it. Here it is:

#include <stdio.h>

main()
{
int ch;

while ((ch = getchar()) != '\n')
putchar(ch);

return 0;
}

First of all, why did they just type main() with no return type specified? That is the first time they have done that in the book and they offer no explanation for it in the text. Second, that if statement in the program above has me confused. I dont quite understand how it is being evaluated. What I thought happens is: ch is assigned the value inputted through the function getchar(). Then, that expression will evaluate to either 0 or 1 to test for truth for the while statement, but that doesnt make sense because then it is being compared to the newline character, which is never going to be 0 or 1. What is going on here?

 

Shuten

Member
Jul 16, 2001
116
0
0
main()
{
int ch;

while ((ch = getchar()) != '\n')
putchar(ch);

return 0;
}

You have to look at the while loop in parts to understand what is going on.
The inner most set of parenthesis is the ch=getchar(). This assigns ch to the
next character read in. Now that ch is set to the character read in it does
this: while (ch != '\n') . If ch is == to \n then the loop will stop. Otherwise
it continues to read in the character and print it back out. The while loop
could also be written as seen below

ch=getchar();
while(ch != '\n')
{
putchar(ch);
ch=getchar();
}
return 0;

 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
function main is a reserved function in C.
The internal definition is an integer return.
 

CSMOOTH

Member
Nov 7, 2001
180
0
0
Here are the simple answers:
1. main() is the same as int main(void)

2. while ((ch = getchar()) != '\n')
putchar(ch);
Evaluate from the inside of the parenthesis out:
ch = getchar() /*this assigns a character to ch*/
then compare ch to '/n' /*this makes sure that you have a character to work with and are not at the end of a string inputted
if ch is not '/n' then you use putchar(ch) and go back to the ch =getchar() part again. If it is '/n' then you head out of the while loop and skip the putchar(ch)

3. The while is actually evaluating if ch == '/n' for the binary 0 or 1 to determine whether or not to execute the while loop