C Language and pitfalls

Source: Internet
Author: User
Tags arithmetic bitwise bitwise operators
The first chapter lexical traps

1.1
if (x = y) is equivalent to assigning the value of Y to X, and then checking whether the value is zero
If the comparison operator = = is written as an assignment operator = because the assignment operator = precedence is less than the logical operator | |, the result is equivalent to assigning the value of the right expression to the left value
1.2
& and | are bitwise operators,&& and | | is a logical operator
1.3
The C compiler reads the characters using the greedy method, reading from left to right, to determine whether the read string can form a symbol, and then continue reading if possible
There can be no white space in the middle of the symbol, and a blank symbol will be interpreted as two symbols.
1.4
Integer constant The first character is 0 and will be treated as a octal number
1.5
A character enclosed in single quotes represents an int integer, and a character enclosed in double quotes represents a pointer
printf (' \ n ') is wrong, printf ("\ n") is correct
Single quotes that contain more than one character cannot be detected because single quotes represent an int, can hold 4 bytes, and finally represent an integer value related to the compiler the second chapter syntax trap

2.1
() priority is higher than *,float *g (); Is a function that returns the type of a floating-point number pointer, float (*H) (), is a function pointer, H points to the return value of a function is a floating-point type
A type converter is equivalent to removing the variable name and semicolon in the declaration, and then wrapping it all in parentheses, such as float (*) ()), which is to convert a function pointer to a type converter that points to a function pointer with the return value of a floating-point type
If the FP is a function pointer, *FP is the function that the pointer points to, *FP () is the way the function is called
Declaring the signal function: void (*signal (int, void (*) (int))) (int) whose parameter is a pointer to a signal processing function, the return value is also a function pointer of that type, and the dereference gets the signal processing function
2.2
The determination of whether the expression is 0 should be explicitly described, as if (flag!= 0)
Operators have the highest priority (), [],.,.
followed by the monocular operator,!, ~, + +,--and so on,
Then the binocular operator, where the arithmetic operator precedence is >> to the shift operator, << High, the relational operator again, the relational operator = =, the!= is lower than the other relational operator
Then the logical operator, the assignment operator, and finally the three-mesh operator
Bit operator ratio && and | | Priority
Note that the order of the Monocular, triple, and assignment operators is from right to left and most of the rest is left to right
2.3
struct declaration to add a semicolon
If the function does not specify a return value, it is returned by default to the INT type
2.4
In a switch statement, each case section ends with a break, or it starts at the current position and executes all the following statements
2.5
function call, even if the function does not take parameters, but also include the argument list, that is, the function name to add ()
2.6
If it is not encapsulated with {}, else will be combined with the most recent mismatch in the same pair of parentheses, chapter III Semantic traps

3.1
In the C language, there is actually only one array, and the size of the array needs to be set by constants in the compiler
The operation of an array is actually done by a pointer, and the array name corresponds to the No. 0 element's pointer
sizeof (p) Gets the actual memory of the array p, while P is converted to pointers in other scenes
We can get the address of the next element through P+i, and the offset in memory of the address is actually an integer multiple of the size of the array element memory.
* (A+i) equivalent to A[i], also equivalent to I[a], as the latter can be understood as * (I+a)
3.2
The use of strcpy and strcat to allocate enough memory first
3.3
Automatically converts an array as a function parameter to a pointer
3.4
The copy pointer does not copy the data that the pointer points to
Modifying string constants is undefined
3.5
NULL is actually defined as 0, and a pointer converted from 0, the compiler guarantees that it is not equal to any valid pointer
0 pointers are not allowed to be dereference
3.6
An array of n elements is labeled 0 to N-1
Represents a range of values with the first entry point and the first out point, where n is the number of elements of an array
--n faster than n--.
3.7
&& and | | Operator discards the evaluation of the right expression when the left value determines the result of the operation
The three-mesh operator will only evaluate one of the expressions
Other operators, especially the assignment operators, are undefined for the order in which the operands are evaluated,
Y[i] = x[i++] and y[i++] = X[i] are all wrong because the left and right order of operations cannot be determined
3.8
& and | are bitwise operators,&& and | | We'll only get 0 and 1.
3.9
Signed operations should pay attention to integer overflow
The check method for if (A + B < 0) is unreliable because the compiler is unsure of the state of the Register
The correct way to check for overflow is if (a > Int_max-b) to ensure that the result is within MAX
3.10
If you do not set the return value for the main function, a random integer is returned
Main return value 0 indicates success of program execution, not 0 indicates failure, so not setting return value interferes with operating system judgmentFourth Chapter Connection

4.1
During compilation, the connector connects each compiled file, all external objects and functions can have only one definition, and cannot have two external objects using the same name, and if declared static, the scope of the object will be limited to the file in which it is located and will not conflict with objects of the same name in other files
4.2
int A; the declaration of a variable appears outside the body of the function, which is called the definition of external object A, which is commonly used global variable
The extern keyword declares the variable only, stating that the variable is defined elsewhere, just a reference to an external variable
Each external object must be defined somewhere, and can only be defined once
4.3
Static restricts the scope of an object to a source file, and functions are declared static and can only be called by functions in the same file
4.4
function to declare or define before calling
If there is float,short,char in the function argument, you cannot omit the description of the argument in the declaration, because the variable will be converted down to an error

char c;
scanf ("%d", &c);
Defines a character variable that reads an integer using scanf because the integer has a larger memory space than the character, which causes memory to be overwritten near C, and the compiler cannot tell
4.5
An external variable is defined in one file, and a different type is declared in another file, and the compiler is not able to detect an error
4.6
Each object is declared only in one place, that is, the file.h header file, which generally puts the declaration of the function and the extern declaration of the external object in the header file, and the definition of the function and the external object in the file.c source file, so that only one definition is required, only file.c files and other files Include "File.h" is legal, the equivalent of other files copied over the Extren declaration Fifth Chapter library function

5.1
EOF is a value defined in stdio.h, different from any character, so that the EOF cannot be stored with char, truncation occurs, resulting in an error in the Judgment
5.2
A call to insert a fseek function between input and output
5.3
Setbuf (stdout, buf) when using fopen and fwirte for input and output operations on a file Specifies a character array buf, using BUF as a buffer for all output written to stdout, when BUF is filled or directly invokes Fflush to output BUF content
The library releases buf at the end of the program, if BUF is defined in the function body, and is released early due to the end of the lifecycle , an error occurs
The workaround is to define the BUF as a static array or an external variable, or dynamically allocate a buffer
if BUF is specified as NULL, then the standard output is set to not require a buffer
5.4
After the success of the library function call, no request will be errno clear zero, also can not guarantee that the call will be set errno, directly check errno is wrong, the correct way is to check the function return value has been wrong, and then check the errno to determine the reason for error
5.5
Signal (signal type, handler function); The signal function specifies that when a signal occurs, handling the event with a specified function is a way to catch an asynchronous event
malloc such complex library functions should not use signal processing functions, because the interrupt malloc function can lead to serious consequences, the relatively safe approach is to set the flag, let the main program know a signal to occur
for arithmetic errors, the signal processing function returned after the failure operation will be performed, The only safe way to print a message and then exit the sixth chapter preprocessor

6.1
A macro definition splits the macro and the actual code based on the first space
6.2
Each parameter of a macro definition and the entire expression are enclosed in parentheses
To ensure that the parameters of the macro have no side effects, the number of times the macro's arguments are evaluated is how many times, if the parameter is X + + such a side effect of the expression will be inconsistent with the expected results, the other way is to use the function to solve
6.3
A macro is not equal to a statement, and writing a macro as a function statement can cause grammatical problems
An Assert macro is an expression that is omitted when the left value is 1 o'clock, when the left value is 0 o'clock to the right, and the function is executed in the process.
6.4
Macros can describe variable types, but using typedef for type definitions is more general
When declaring multiple pointers at the same time, the macro is simply a copy of the code, only the first variable is declared as a pointer, and the other is the pointer's dereference type. Seventh chapter portability Defects

7.1
Some compilers cannot specify parameter types in a declaration
7.2
For identifiers, some compilers can only distinguish the first 6 characters and are case-insensitive
7.3
Some variable lengths are not fixed on different machines, so it is necessary to change the type definition by using typedef to declare such variables.
7.4
When converting a character C to an unsigned integer with (unsigned) c, an error occurs, and C is first converted to an int integer
The correct approach is to use (unsigned char) c conversion to convert directly to an unsigned integer
7.5
The unsigned number is moved to the right, the vacancy is filled with 0, and the signed number is filled with the sign bit
If the shifted object has an n bit length, the operand for each shift is within [0,n-1]
>>1 is much faster than/2.
7.6
To prevent the dereference of NULL pointers, you should move the program to a machine that does not allow read memory location 0
7.7
Negative modulus may come out is also a negative number, to make the remainder in [0,hashsize), should be judged on the remainder, less than 0 plus hashsize can
A better approach is to ensure that dividend is avoided negatively and that unsigned numbers are used
7.8
Rand range may be different on different machines
7.9
The case conversion function has a different version of the letter depending on whether the argument is
7.10
ReAlloc can resize the length of a piece of memory
Some systems are freed of memory that can be temporarily retained
7.11
numeric conversion to character using n+ ' 0 ' can also be an error, the correct approach is to use string constants as the character chart "0123456789" [n]
The operation of a signed number n=-n may overflow because most integer data can only express the -2^k~2^k-1 range of data, overflow the minimum operation, and the correct operation is to assign unsigned numbers to operate
For signed number modulo, to ensure that the remainder is positive, and to prevent overflow, we should first take the divisor is negative, take the model after the negative remainder, and then take the opposite number

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.