Chapter 2 Introducing C
#2019.7.15#
A Simple Example of C
The Example Explained
Pass 1: Quick Synopsis
Pass 2: Program Details
#include Directives and Header Files
#include<stdio.h>:
#include
- An example of preprocessor directive.
- It’s a cut-and -paste operation.
stdio.h file (standard input/output header)
- It contains info about I/O functions, such as printf().
- Header files help guide the compiler in putting your program together correctly.
(The actual code of function is in a library file of precompiled code, not in a header file)
The main() Function
int main(void)
- A C program always begins execution with the function called main().
- The int is the main() function’s return type (return to the OS).
- The parentheses generally enclose info being passed along to the function(Nothing is passed along to the function main(), so there is a void in parentheses).
Other format:
main()
void main()
shouldn’t be used even if several compilers tolerate them.
Comments:
/*
*/
the end mark could not be omitted and it allows comments to spread to more than one line.
‘//’ welcome by C++ and Java, using to create comments that are confined to a single line.
Brace, Bodies and Blocks
{
…
}
- Using to delimit functions
- Also be used to gather statements within a functions into a unit or block.
#2019.7.16#
Declarations
int num;
- The semicolon ay the end of the line identified the lines as a C statement or instruction. The semicolon is part of the statement, not just a separator between statements as it is in Pascal.
- The word num in this example is an identifier—that is, a name you select for a variable, a function, or some other entity.
- Following C++, C99 and C11 let you place declarations about anywhere in the block as long as you declare them before you use them (traditionally, no other kind of statements are allowed to come before any of the declaration).
Data Type
integers, characters, and floating point.
Name Choice
- The compilers only consider the first 63 characters as significant.
- The characters at your disposal are lowercase letters, uppercase letters, digits, and the underscore(_). The first character must be a letter or an underscore.
- It is better to avoid the usage of one or two initial underscore, for them might be reserved as library identifiers or in the OS.
- C names are case sensitive
Four Good Reasons to Declare Variables
Assignment
num=1;
The assignment statement assigns a value from the right side to the left side.
The printf() Function
- What lies between the double quotation marks is the actual argument.
- \n, the newline character—an example of an
escape sequence - %d, % means it is a placeholder, and d
means to print a decimal(base 10) integer.
Return Statement
Return 0;
The Structure of a Simple Program
Tips on Making Your Programs Readable
- Choosing meaningful variable names;
- use comments;
- using blank line to separate one conceptual section of a function
from one another; - use one line per statement