C15. C Layout of a C Programm

Layout of a C Program
We can think of a C program as a series of tokens groups of characters that can't be split up without changing their meaning. Identifiers and keywords are tokens. So are operators like + and - punctuation marks such as the comma and semico­lon, and string literals. For example, the statement
printf(“Height: %d\n”, height);
consists of seven tokens:
printf ( “Height: %d\n” , height )    ;

Formatted Input/output:
The printf Function
The printf function is designed to display the contents of a string, known as the format string, with values possibly inserted at specified points in the string. When it's called, printf must be supplied with the format string, followed by any val­ues that are to be inserted into the string during printing:
printf {string, expr\, expr2, ...) ;
The values displayed can be constants, variables, or more complicated expressions. There's no limit on the number of values that can be printed by a single call of printf.
The formal string may contain both ordinary characters and conversion speci­fications, which begin with the % character. A conversion specification is a place­holder representing a value to be filled in during printing. The information that follows the % character specifies how the value is converted from its internal form (binary) to printed form (characters) that's where the term “conversion specifica­tion” comes from. For example, the conversion specification %d specifies that printf is to convert an int value from binary to a string of decimal digits, while %f does the same for a float value.

C compilers aren't required to check that the number of conversion specifications in a format string matches the number of output items. The following call of printf has more conversion specifications than values to be printed:
printf(“%d %d\n”, i); /*** WRONG ***/
printf will print the value of i correctly, then print a second (meaningless) integer value. A call with too few conversion specifications has similar problems:
printf(“%d\n”, i, j); /*** WRONG ***/
In this case, printf prints the value of i but doesn't show the value of j.
Furthermore, compilers aren't required to check that a conversion specifica­tion is appropriate for the type of item being printed. If the programmer uses an incorrect specification, the program will simply produce meaningless output. Con­sider the following call of printf, in which the int variable i and the float variable x are in the wrong order:
printf(“%f %d\n”, i, j) ; /*** WRONG ***/
Since printf must obey the format string, it will dutifully display a float value, followed by an int value. Unfortunately, both will be meaningless.

No comments: