Notes on modern methods of C language programming

Source: Internet
Author: User

C Programming: a modern approach, Second Edition

1. For C Programs, it usually includes the following three steps (usually automatically implemented, so people often find that this work is not too difficult ):

    • Preprocessing. First, the program is handed over to the Preprocessor to execute commands starting with # (usually called commands), add content to the program, and modify the program.
    • Compile. The modified program can now enter the compiler, which translates the program into machine commands (that is, the target code ). Such a program cannot run.
    • Link. In the last step, the linker integrates the target code generated by the compiler with other additional code to generate a fully executable program.

2. The C language has been lacking for many yearsBoolean TypeThis problem is solved in c99. It provides the _ bool type and can only be assigned 0 or 1 values. If the non-zero value is stored, the variable is assigned 1 values; c99 also provides a header file <stdbool. h> to make it easier to operate boolean values.

/**Name : pun.c*Purpose: Prints a bad pun*Author: Albert,K.N.King*/#include <stdio.h>//#include <stdbool.h>int main(void) /*Beginning of main program*/{//bool flag = true;_Bool flag = 1;if(flag) printf("To C, or not to C ,that is the question!\n");return 0;}

[scwangj@LB270108 simple]$ gcc test.c -o test[scwangj@LB270108 simple]$ ./testTo C, or not to C ,that is the question![scwangj@LB270108 simple]$

3. The pre-processor command is calledCommand(Directive), the Command executed when the program is running is calledStatement(Statement ).

4,Identifier, You may not think:

    • An identifier that starts with an underline and an upper-case letter, or is switched by two underlines. It is an identifier reserved for the standard library. The program cannot use this identifier for any purpose.
    • Identifiers starting with an underscore are retained as identifiers and tags with file scopes. This type of identifier should not be used unless declared within the function.
    • All identifiers with external links in the standard library are retained as identifiers with external links. In particular, the names of all standard library functions are retained. Therefore, even if the file does not contain <stdio. h>, you should not define an external function named printf, because a function with the same name already exists in the standard library.

5. Return 0 orExit (0)Both are program termination, which is completely equivalent. The exit function is included in the header file <stdlib. h>.

6. It contains the decimal point but does notConstant ending with FIs double type, it is more accurate than Float Type value storage. If F is not added, the compiler may generate a warning message indicating that the number of variables stored in the float variable may exceed the value range of the variable.

7,About printf.The C language compiler does not check whether the number of conversion instructions in the format string matches the number of output items. For example

Printf ("% d, % d \ n", I); The value of variable I is displayed correctly, followed by another (meaningless) integer.

Printf ("% d \ n", I, j); the value of variable I is displayed, but the value of variable J is not displayed.

The C language does not check whether the conversion is suitable for the Data Type of the item to be displayed. The following printf function indicates that the sequence rotation of int and float variables X is incorrect:

Printf ("% F, % d \ n", I, x); because the printf function must be subject to the format string, it will display a float value in the field, next is an int value. However, these two values will be meaningless.

8,About scanf.The scanf function is essentially a "pattern matching" function, trying to match the input character group with the conversion description. When looking for the starting position of the data, it will ignore white space characters (including space characters, horizontal and vertical tabs, page breaks, and line breaks ). When the scanf function encounters a character that cannot belong to the current item, it "puts the character back to the original place" to read it again when scanning the next input item or the next call to the scanf function. As shown in the following four numbers (Use☼Line Break ):

1-4873-4.0e2☼

Use the following scanf function call:

Scanf ("% d % F", & I, & J, & X, & Y );

Therefore, the first non-empty input character is 1. Because the integer can start from 1, scanf then reads the next character, that is,-, which cannot appear in the integer, therefore, save 1 to the variable I, and place the character-back in the original position. Then scanf reads the characters-, 2, 0 ,., because the decimal point cannot be included, scanf saves-20 to variable J and places the decimal point back to the original place. Then, it reads the characters ., 3,-, because the floating point number cannot have a negative number behind the number, scanf saves 0.3 to the variable X, and places the character-back to the original position. scanf finally saves-4.0x10 ^ 3 to the variable Y, place the linefeed back to its original location.

Q &:

I cannot understand how the scanf function puts the character back to its original position and reads it again later?

When a user inputs data from the keyboard, the program does not read the input. Instead, it places the user input in a hidden buffer zone and is read by the scanf function. The scanf function puts the characters back in the buffer for subsequent reading.

9. When the operator/and operator % are used for negative operands, the result is difficult to determine. It is best to avoid writing programs that depend on the behavior defined by the implementation.

10,Auto-increment and auto-increment Operators. ++ I means "auto increment 1 now", while I ++ means "first use the original value of I and then auto increment 1 later ", we can rest assured that I will perform auto-increment before the next statement is executed.

11. According to the C standard, statements like C = (B = a + 2)-(A = 1); and J = I * I ++; will cause"Undefine behavior )"When undefined behaviors occur in the program, the consequences are unpredictable. The compilation results provided by different compilers may be different, but this is not the only possible thing: first, the program may not be able to pass compilation, and even if it passes compilation, it may not be able to run, even if it can run, it may crash, be unstable, or produce meaningless results. In other words, we should avoid undefined behavior like avoiding plague.

12,"Hanging else" problem. In C language, the else clause should belong to the IF statement closest to it and not matching other else statements. For example

if (y != 0) if(x != 0)result = x / y;elseprintf("Error: y is equal to 0 !\n");

The correct indent format should be as follows:

if (y != 0) if(x != 0)result = x / y;elseprintf("Error: y is equal to 0 !\n");

You can enclose the inner if statement in curly brackets:

if (y != 0) {if(x != 0)result = x / y;elseprintf("Error: y is equal to 0 !\n");}

13. AboutConditional expressions

Q: If I is an int variable and F is a float variable, then the conditional expression (I> 0? I: F) which type of value is used?

A: As shown in the problem, when the values of the in and float types are mixed in a conditional expression, the expression type is float. If I> 0 is true, the value after I is converted to float is the value of the expression.

14,About goto statements. A goto statement is not a natural devil, but usually it has a better alternative. A program that uses too many goto statements quickly degrades to "spam code", because the control can jump freely. Because the GOTO statement can both jump forward and backward, it makes the program difficult to read, while the break statement only jumps backward, and the continue only jumps forward. The GOTO statement makes the program difficult to modify, because it may make a piece of code for a variety of different purposes. The other c99 does not allow the GOTO statement to bypass the variable-length array statement, because during program execution, when the variable-length array declaration is encountered, the variable-length array is usually allocated memory space, bypassing the variable-length array statement with the GOTO statement may cause the program to access elements in the array with unallocated space.

15. About strings.

    • The C language allows subscript on the pointer, so you can subscript the string literal: Char ch; CH = "ABC" [1]; then the CH value is B.
    • Char digit_to_hex_char (INT digit) {return "0123456789 abcdef" [digit];} This function converts the numbers 0-15 to the equivalent hexadecimal character format.
    • Do not use characters when strings are needed (or vice versa ). For example, printf ("\ n"); is valid, while printf ('\ n'); is invalid.
    • When declaring an array of characters used to store strings, always ensure that the length of the array is one more character than the length of the string, because the C language requires that each string should end with a null character, otherwise, there may be unexpected consequences. The length of the string depends on the location of the null character, rather than the length of the character array used to store the string.

16. The scanf and gets functions read strings.

    • The scafn function skips the white space characters, reads and stores the characters until the white space occurs. The scanf function always stores an empty character at the end of the string.
    • Using the scanf function to read strings will never contain white spaces. Therefore, the scanf function usually does not read a whole line of input. A line break will stop the scanf function reading, and a space character or tab will also produce the same result. To read a whole line of input at a time, you can use the gets function, which also stores an empty character at the end of the string.
    • Gets is different from scanf functions:
      • The gets function does not skip blank characters before starting to read the string (the scanf function will skip)
      • The gets function will continue to read the data until the line break is found (the scanf function will stop any blank characters ). In addition, the gets function ignores the line break and does not store it in the array. It replaces the line break with null characters.

17,

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.