Re-reading of the C programming language (2): Introduction

Source: Internet
Author: User
Tags file copy integer division

This chapter is mainly a summary of the introduction of C language, through the actual program to introduce the basic elements of C language. For specific details, further chapters will be presented.

(1) The only way to learn a new programming language is to use it to write programs.

/* Copyright (C) [email protected] */#include <stdio.h>main () {printf ("Hello, world\n");}

(2) in Unix, to run the above code, the first to establish the program in a file, and ". C" as the file extension. The source program is compiled with the following command, and if compiled, the a.out executable is generated in the current directory. Execute the program directly.


(3) cc is actually a link to the system C compiler, it can be seen that in my system cc is actually GCC's symbolic connection.


(4) A C language program, regardless of its size, is made up of functions and variables.

(5) The main function is a special function name, and each program executes from the beginning of the main function, which means that each program must contain a main function at a location.

(6) One way to exchange data between functions is to call a function to provide a list of values (parameters) to the called function.

(7) A sequence of characters enclosed in double quotation marks is called a string or string constant.

(8) An escape character sequence similar to "\ n" provides a common extensible mechanism for characters that cannot be entered or invisible characters.

The following is a procedure to convert Fahrenheit to Celsius temperature:

/* Copyright (C) [email protected] */#include <stdio.h>main () {int Fahr, celsius;int lower, upper, Step;lower = 0;u Pper = 300;step = 20;fahr = Lower;while (Fahr <= upper) {Celsius = 5 * (fahr-32)/9;printf ("%d\t%d\n", Fahr, Celsius ); Fahr = Fahr + Step;}}

(9) The sequence of characters contained in/* and/* is ignored by the compiler and can therefore be used as a comment.

(10) Each clause ends with a semicolon.

(11) Although the C compiler does not care about the appearance of the program, the correct indentation and proper space-preserving program design styles are important to the readability of the program.

(12) It is recommended to write only one statement per line, and add a space character to each side of the operator, which makes the associative relationship of the operation clearer.

(13) in the C language and many other languages, integer division executes the rounding, and any fractional portion of the result is discarded. (So the above code uses 5 * (FAHR-3)/9 instead of 5/9 * (fahr-3))

The printf function is not part of the C language itself, and the C language itself does not define input/input functionality. The printf function is just a useful function in standard library functions. The ANSI C standard defines the behavior of the printf function.

(15) Because the output data is not right-aligned, so the output is not very beautiful. The printf statements in the original program can be modified as follows, by specifying the print width in%d, the printed number will be right-aligned within the print area.

printf ("%3d\t%6d\n", Fahr, Celsius);

Because the above procedure uses the integer variable to calculate, causes the accuracy to be inaccurate, the following procedure uses the floating-point number to calculate:

/* Copyright (C) [email protected] */#include <stdio.h>main () {float Fahr, celsius;int lower, upper, Step;lower = 0 ; upper = 300;step = 20;fahr = Lower;while (Fahr <= upper) {Celsius = 5.0 * (fahr-32.0)/9.0;printf ("%3.0f\t%6.1f\n", Fahr, celsius); Fahr + = Step;}}

(16) The decimal point in the constant indicates that the constant is a floating-point number, so the two floating-point numbers are divided and the result is not taken.

(17) Even if the floating-point constant is an integer value, it is best to add an explicit decimal point to it when writing, which can emphasize its floating-point character.

(18) For a particular task, we can write programs in a variety of ways.

The following is a simpler way to implement the program:

/* Copyright (C) fuchenc[email protected] */#include <stdio.h>main () {    int fahr;    for (Fahr = 0; Fahr <=; Fahr + =)    {        printf ("%3d\t%6.1f\n", Fahr, 5.0/9.0 * (fahr-32));}    }

A general rule for C: a more complex expression of that type can be used where a value of a type variable is allowed.

The For statement is more appropriate for both the initialization and the growth step is a single statement and is logically related, because it centralizes the loop control statements and is more compact than the while statement.

(21) The use of magic numbers in a program is not a good habit, it can hardly provide any information to people who read the program, and makes it more difficult to modify the program.

Here's a better way to achieve this:

/* Copyright (C) [email protected] */#include <stdio.h> #define LOWER 0#define UPPER 300#define STEP 20main () {int F Ahr;for (Fahr = LOWER; Fahr <= UPPER; Fahr + = STEP) {printf ("%3d\t%6.1f\n", Fahr, 5.0/9.0 * (fahr-32));}}

The Define directive can define a symbol name as a specific string. Once defined, all the names in the program that are defined in the define (neither quoted nor part of other names) are replaced with the corresponding replacement text.

(23) Usually symbolic constants are spelled in uppercase letters, which can be easily distinguished from variable names spelled in lowercase letters.

There is no semicolon at the end of the define instruction.

Here is a file copy program:

/* Copyright (c) [email protected] */#include <stdio.h>main () {int C;while ((c = GetChar ())! = EOF) {Putchar (c);}}

(25) The input/output model provided by the standard library is very simple. Regardless of where the text is entered and where it is exported, its input/output is handled in the same way as the character stream.

(26) A text stream is a sequence of characters consisting of multiple lines of characters, each of which consists of 0 or more characters, and the end of the line is a newline character. The standard library is responsible for enabling the input/output stream to follow this model.

The GetChar function reads the next input character from the text stream and returns it as the result value. The Putchar function outputs the shaping variable as a character to the standard output.

(28) characters are stored in bit mode inside the machine, regardless of the form of the keyboard, screen, or anywhere else.

The char type is designed to store character data, and of course any integral type can also be used to store character data. The above code takes int because it is possible for the GetChar function to read the file Terminator (EOF), which means that the input ends. The specific values of EOF are related to the platform, but can be guaranteed to be different from any char type. So it is possible that EOF is not represented by the char type, so you must use int to store the return value of the GetChar in order to correctly handle the case where EOF is returned.

(30) An assignment operation is an expression and has a value, that is, the value saved by the left variable after the assignment.

(31) The parentheses on both sides of an assignment expression cannot be omitted, because the non-equal operator (! =) has precedence over the assignment operator (=).

The following is a character-counting program that uses double to handle more input:

/* Copyright (C) [email protected] */#include <stdio.h>main () {double nc;for (nc = 0.0; GetChar ()! = EOF; nc++) {;/ /null}printf ("%.0f\n", NC);}

(32) When printing floating-point numbers, the decimal and fractional parts are forced to not print by%.0f.

(33) A separate sub-claim is an empty statement.

The following is a line statistic program:

/* Copyright (c) [email protected] */#include <stdio.h>main () {int C, NL;NL = 0;while ((c = GetChar ()) = EOF) {if (c = = ' \ n ') {++nl;}} printf ("%d\n", NL);}

(34) The characters in the single quotation mark represent an integer value equal to the corresponding value in the machine character set of the character, which we call a character constant.

(35) The escape character is also a valid character constant.

The following is a word counting program, which is also the backbone of the WC program in UNIX systems:

/* Copyright (C) [email protected] */#include <stdio.h> #define State_out 0#define state_in 1main () {int NC, NL, NW, C, state;nc = NL = NW = 0;state = State_out;while ((c = GetChar ())! = EOF) {++nc;if (c = = ' \ n ') {++nl;} if (c = = ' | | c = = ' \ t ' | | c = = ' \ n ') {state = State_out;} else if (state = = state_out) {state = STATE_IN;++NW;}} printf ("%d%d%d\n", NC, NL, NW);}

(36) If the magic number in the program appears in the form of symbolic constants, it is much easier to make a lot of changes to the program.

(37) The binding order of assignment is from right to left.

Here is a program that counts individual numbers, whitespace, and all other characters:

/* Copyright (C) [email protected] */#include <stdio.h>main () {int I, C, nwhite, nother;int ndigit[10];nwhite = not her = 0;for (i = 0; i < ten; i++) {ndigit[i] = 0;} while ((c = GetChar ()) = EOF) {if (c = = ' | | c = = ' \ t ' | | c = = ' \ n ') {++nwhite;} else if (c >= ' 0 ' && C <= ' 9 ') {++ndigit[c-' 0 '];} else {++nother;}} printf ("digits ="); for (i = 0; i <; i++) {printf ("%d", Ndigit[i]);} printf (", Nwhite =%d, nother =%d\n", Nwhite, nother);}

(38) In the C language, array subscripts always start at 0. An array subscript can be any integer expression.

(39) The above procedure normal operation, relying on such a hypothesis: ' 0 ', ' 1 ', ' 2 ' ... ' 9 ' has a continuously incrementing value. Fortunately, in all character sets, this hypothesis is true.

Characters of type char are small integers, so variables and constants of type char are equivalent to variables and constants of type int in an arithmetic expression.

The following is a program that computes a power operation (the program is not robust enough):

/* Copyright (C) [email protected] */#include <stdio.h>int power (int m, int n); main () {int i;for (i = 0; i < 10; i++) {printf ("%d,%d,%d\n", I, power (2, I), power ( -3, i));} return 0;} Intpower (int base, int n) {int I, p;p = 1;for (i = 0; i < n; i++) {p = base * p;} return p;}

(41) The function provides an easy way to calculate the encapsulation, since the use of the function does not need to consider how it is implemented.

(42) Function definitions can appear in any order in a source file or multiple source files, but the same function cannot be split into multiple files.

(43) The name used by the function parameter is valid only within the function.

Main itself is also a function, so you can also return a value to its caller, which is actually the execution environment of the program. In general, a return value of 0 indicates a normal termination, and a return value of 0 indicates an exception condition or an end-of-error.

(45) The function prototype must be consistent with the function definition and usage. If the definition, usage, and function prototypes of the function are inconsistent, an error will occur.

(46) Parameter names in function prototypes are optional, but proper parameter names can be very descriptive, so we always specify parameter names in function prototypes.

This program is implemented using the earlier version of the C language:

/* Copyright (C) [email protected] */#include <stdio.h>int power (); main () {int i;for (i = 0; i <; i++) {print F ("%d,%d,%d\n", I, power (2, I), power ( -3, i));} return 0;} Intpower (base, n) int base, n; {int I, p;p = 1;for (i = 0; i < n; i++) {p = base * p;} return p;}

The biggest difference between ANSI C and earlier versions of C is that the declaration of a function differs from the way it is defined.

(48) in the original definition of C, the argument list is not allowed in the function declaration, so the compiler cannot check the legality of the function call at this time. In the function prototype syntax defined in ANSI C, the compiler can easily detect errors in the number and type of parameters in a function call.

ANSI C still supports legacy function declarations and definitions, but when using modern compilers, it is best to use a new type of function prototype declaration.

(50) in the C language, all function parameters are passed by value. In the C language, the called function cannot directly modify the value of a variable in the primary function, but only the value of its own private temporary copy.

(51) The value of the call is greater than the disadvantage, in the called function, the parameters can be considered as easy to initialize the local variables, so the additional use of fewer variables, which makes the program more concise.

(52) If it is an array parameter, the situation is different. When you use an array name as an argument, the value passed to the function is the address of the first element of the array-it does not copy the array elements themselves.

(53) The default return value type of the function is int.

The following program reads a set of lines of text and prints the longest line of text (the program is not robust enough):

/* Copyright (C) [email protected] */#include <stdio.h> #define MAXLINE 1000int get_line (char line[], int MAXLINE); void copy (char to[], Char from[]), main () {int len, Max;char line[maxline];char longest[maxline];len = max = 0;while (len = Get_line (line, MAXLINE))! = 0) {if (len > Max) {copy (longest, line); max = Len;}} if (Max > 0) {printf ("%s", longest);} return 0;}  Intget_line (char line[], int maxline) {int C, i;for (i = 0; i < maxline-1 && (c = GetChar ())! = EOF && C ! = ' \ n '; i++) {Line[i] = C;} if (c = = ' \ n ') {line[i++] = C;} Line[i] = ' + '; return i;} Voidcopy (char to[], char from[]) {int i;i = 0;while ((to[i] = From[i])! = ' + ') {i++;}}

String constants in the C language, stored as character arrays, each of the elements in the array stores the individual characters of the string, and ends with a '/s ' flag string. The format specification%s in the printf function specifies that the corresponding parameter must be a string that is represented in this form.

(55) An automatic variable exists only during a function call. If an automatic variable is not assigned a value, it holds an invalid value.

(56) Variables that can be accessed through variable names in all functions are called external variables, and external variables can be accessed globally, so that data can be exchanged between functions through external variables, rather than using parameter tables.

(57) External variables persist during program execution.

(58) An external variable must be defined outside of all functions and can be defined only once, and the compiler assigns a storage unit to it after the definition.

(59) In each function that requires access to an external variable, the corresponding external variable must be declared, declared with an extern statement, or implicitly declared by context.

(60) in the source file, if the definition of an external variable appears before the function that uses it, there is no need to declare the external variable with an extern statement in this function.

(+) The ANSI C language sees the empty argument list as the old version of the C language, and no longer checks the parameter table. In ANSI C, if you want to declare an empty parameter table, you must display the declaration using the keyword void.

(62) Careful use of definitions and declarations. A definition represents creating a variable or allocating a storage unit, whereas a declaration is a description of the nature of the variable and does not allocate a storage unit.

(63) Excessive reliance on external variables can lead to a certain risk because it blurs the data relationship in the program and makes it difficult to modify the program. .


Re-reading of the C programming language (2): Introduction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.