영어로 읽는 코딩

06 [C] line counting

#include <stdio.h>

/*count lines in input*/

int main() {
    int c, nl;

	nl = 0;
	while ((c = getchar()) != EOF)
		if (c == '\n')
			++nl;
	printf("%d\n", nl);
}

/*The C Programming Language (second edition, Prentice Hall) 
  by Brian W. Kernighan and Dennis M. RitchieS*/

 

* 코드 설명

The body of the while now consists of an if, which in turn controls the increment ++nl. The if statement tests the parenthesized condition, and if the condition is true, executes the statement (or group of statements in braces) that follows. We have again indented to show what is controlled by what.

 

* == / =

The double equals sign == is the C notation for “ is equal to” {like Pascal’s single = or Fortran’s . EQ. ). This symbol is used to distinguish the equality test from the single = that C uses for assignment. A word of caution: newcomers to C occasionally write = when they mean ==. As we will see in Chapter 2, the result is usually a legal expression, so you will get no warning.

 

* ' ' ASCII

A character written between single quotes represents an integer value equal to the numerical value of the character in the machine’s character set. This is called a character constant, although it is just another way to write a small integer. So, for example, ’A' is a character constant; in the ASCII character set its value is 65, the internal representation of the character A. Of course ’A’ is to be preferred over 65: its meaning is obvious, and it is independent of a particular character set.

 

* 이스케이프 문자 (escape character) \

The escape sequences used in string constants are also legal in character constants, so '\n' stands for the value of the newline character, which is 10 in ASCII. You should note carefully that '\n’ is a single character, and in expressions· is just an integer; on the other hand, ”\n” is a string constant that happens to contain only one character. The topic of strings versus characters is discussed further in Chapter 2.

 

[The C Programming Language (second edition, Prentice Hall) by Brian W. Kernighan and Dennis M. Ritchie]

댓글

댓글 본문
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기