C traps and pitfalls notes

Source: Internet
Author: User
This book contains more than 100 pages. Article . However, many of the problems pointed out are indeed prone to mistakes in the written examination.

--------------------------------------------------------------------
Chapter 2 lexical traps

1.1 = and =

1.3 greedy law for lexical analysis"
The compiler reads characters from left to right. Each symbol contains as many characters as possible until it is not a character.

For example:
A --- B is equivalent to a ---B

A/* B is not a/(* B), but/* as a annotator

1.4 Integer constants

An integer starting with 0 is in octal format.

For example:
014 is in octal format. Do not mistakenly think of it as in decimal format.

1.5 characters and strings

Single quotes-ASCII characters, actuallyInteger
Double quotation mark (double quotation mark)-pointing to the start character of an anonymous character arrayPointerThe array is initialized with the referenced characters and additional '\ 0'

In addition, most compilers allow a character constant to contain multiple characters. Borland C ++ only takes the first character. In VC 6.0 and GCC, the subsequent characters overwrite the previous character. The last character is obtained.

Example: (GCC 3.5)
Char CH = 'yes ';
Cout <ch; // output: S, but with warning

Exercise questions:
1-1. Some C compilers allow nested comments. Please write a testProgram, Requirement: whether or not the compiler allows nested comments, the program can be compiled normally (no error message), but the program execution results are different in both cases.

1-3. n --> 0?
(N --)> 0 greedy rule

1-4 what is the meaning of a ++ B?
(A ++) + B
However, it is worth mentioning that in modern compilers, this formula is invalid.

Why?
You can view the prototype of operator ++ (INT): const int operator ++ (INT)
The returned result is a temporary copy of the const type and is. The reason why the return is const type is to take the return value as the left value, so as to prevent the occurrence of such formulas
Summary:A ++ cannot be left-side.

Bytes ---------------------------------------------------------------------------------------
Chapter 4 syntax traps

2.1 understand the function declaration
Declaration)
Declaration statement structure: Type + A set of similar expression declarations (declarator)

Float F, G; // expression F. The value of G is a floating point, that is, f, and G is a floating point.
Float ff (); // The expression ff () is a floating point number, that is, FF is a function that returns a floating point number.
Float * PF; // * PF is a floating point number, that is, PF is a pointer to the floating point type.
More complex,
Float * g (), (* H )();
Based on the above and the () priority is greater than *, it is easy to know that G is a function and the return type is floating point pointer (float *)
H is a function pointer, and the function return type is float.
(Float (* H) () is a type conversion character.

Let's look at it again:
(* (Void (*) () 0 )()
Essentially:
Void (* FP) (); // declare a function pointer
Typedef void (* fp_type) (); // for simplifying, otherwise always need void (*)()
Conv_0 = (fp_type) 0; // converse function 0 into function conv_o
(* Conv_0) (); // using the conversed Function

Let's take a look at the signal function declared in <signal. h>.
Void (* signal (INT, void (*) (INT)
First, use typedef to simplify,
Typedef void (* handler_type) (INT)
Void (* signal (INT, handler_type) (INT)
Further handler_type signal (INT, handler_type );

2.3 semicolon ending with a statement
1) write more semicolons
If (X [I]> big );
Big = x [I]
This is easy to identify.
Check again
2) The semicolon is missing If (N <   3 )
Return
Logrec . Date = X [ 0 ];
Logrec . Time   = X [ 1 ];
Logrec . Code = X [ 2 ];

Do you see the problem?

Continue to look at the following classic:StructLogrec
{
IntDate;
IntTime;
IntCode;
}

Main ()
{
//
}

Note: This question has already appeared

2.4 swith statement
This is an old saying.

That is, whether the break after case is correct.

First, you must understand one thing: You can regard (Case :) as the statement label, just like the label in the Assembly. After the switch, jump to the matching case and execute it sequentially. If you encounter a case later, you will ignore it.

Of course, except for those that intentionally do not require break in programming

2.6 problems caused by "blank suspension" else

See Code : If (x = 0 )
If (Y = 0 ) error ();
else {< br> Z = x + Y;
F ( & Z);
}

This code may be quite different from your intention, because else matches the latest if

It's easy to prevent this type of problem. As long as if is used every time, else uses {}

---------------------------------------------------------
Chapter 2 semantic traps

3.1 pointers and Arrays

Note:
1) C language only has one-dimensional array, and the array size must be determined as a constant during compilation. A two-dimensional array is implemented through an array element or an array's one-dimensional array.
2) For an array, only two things can be done: determine the size of the array and obtain the pointer pointing to the first element of the array. For other operations, the following computation is performed by pointer.

Int A [3]; // The array element is of the int type.
Struct
{
Int P [4];
Double X;
} B [17]; // The array element is a struct.
Int calendar [12] [31];
// Array of 12 elements. Each element is an array of 31 elements.
// Not: array of 31 elements. Each element is an array of 12 elements.

Remember: The array name is a pointer to the first element of the array.
For example, int A [11]; // The type of A is (int *)
Int * PTR;
PTR =;
But PTR = & A; is invalid. Here, the type of & A is int (*) [], that is, the pointer to the array. This operation is considered invalid during most compilation periods, or make it equal to

In C, A + I and I + A have the same meaning, but the latter is not recommended.

The following describes multi-dimensional arrays:
Int calendar [12] [31];
Int * P;
Int I;

It is easy to know what calendar [4] means: Calendar [4] represents the 5th elements of the calendar ar array and is one of 12 arrays with 31 elements.
Sizeof (calendar [4]) returns 31 × sizeof (INT)

In this example, the calendar name is converted to a pointer to an array, whose type is int (*) [31].
So P = calendar; is invalid

INT (* monthp) [31];
Monthp = calendar; // OK

Calendar [month] [Day] = 0;
Equivalent
* (Calendar + month) + day) = 0;
How can we analyze this?
First, calendar + month is a pointer to one of the 12 elements. By referencing it, it is its element (and the element is an array), so * (calendar + month) is a pointer to the first element of the array containing 31 elements, and then offset and then unreference to obtain the final int element.

Summary:
1) array name indicates a pointer to the first element. The type is an element type pointer.
2) Get the address of the array name, which is a pointer to the array, and the type is an array pointer

3.2 non-array pointer-string

String constant: represents the address of a memory zone that contains all characters in the string plus an extra null character ('\ 0.

Generally, string constants are saved in character arrays and are read-only.

String operation functions:
Size_t strlen (char *); // calculate the string length until '\ 0' is encountered.' \ 0' is not included'
Int strcpy (char * DEST, const char * SRC );
Int strcat (char * DEST, char * SRC );

Note that the output parameter DEST must be pre-allocated and have enough space to accommodate

3.3 array as function parameter

Automatically convert to pointer

3.6 boundary computing and asymmetric Boundary

This topic is worth exploring

3.7 order of Value

In C, there are only four operators (&, || ,? : And,) specifies the order of values. For other operators, do not mistakenly assume the order of values. Their order of value is undefined.

For example:
I = 0;
While (I <n)
Y [I] = x [I ++];

Here, the address of Y [I] is not guaranteed to be evaluated before I auto-increment.

3.9 Integer Overflow

There are two types of integer arithmetic operations in C language: signed and unsigned.

There is no overflow between the two unsigned number operations.

In arithmetic operations, one is the number of symbols and the other is the number of unsigned symbols. Then, the number is converted to the number of unsigned symbols, and overflow is impossible during the operation.

Overflow may occur in two signed number operations. When overflow occurs, the overflow result is undefined.

So how can we detect whether overflow exists?
See the following method:
Int A, B;
If (a + B <0)
// Do something

This method is unreliable because any assumptions made on the overflow results are unreliable.

The correct method:
# Include <limits. h>
Int A, B;
If (unsigned) A + (unsigned) B> int_max)
//...
Or
If (A> int_max-B)
//...

Bytes --------------------------------------------------------------------------------------
Chapter 2 connection

4.2 declaration and definition

The statement below:
Int;
If it appears outside of all function bodies (including the main function), it is defined as an external object A and its initial value is 0 by default.

The statement below:
Int A = 7;
Specify the initial value when defining.

The statement below:
Extern int;
It is not the definition of a. It means that A is an external integer variable and its storage space is allocated elsewhere in the program.

Typical cases:
// File1.c
Int A = 7;

// File2.c
Int A = 9;

In this case, an error is reported during connection, because the definition can only be one time, but the Declaration can be many

4.3 naming conflicts and static Modifiers

Static limits the scope of variables or functions in a source file.

4.5 check external variables

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.