Macro // const // sizeof // static // volatile and other keywords usage

Source: Internet
Author: User
Tags define find

I. macro definition: Mainly some Syntax problems and skills

For example:

# Define find (S, e) (size_t) & (struct s *) (0)-> E) // calculates the offset of the variable in the structure to the struct.

# Define seconds_per_year (360*24*60*60) UL // calculate the number of seconds in a year

# Define min (A, B) (a) <= (B ))? (A) :( B) // calculate the minimum value

# Define swap (a, B) {A = a ^ B; B = a ^ B; A = a ^ B;} // note that {} is not ()

Note: portability is considered as much as possible. Because the code may run on 16-bit machines or 32-bit machines, size_t and UL are both based on portability considerations.

 

Ii. Const usage: defines constants and modifies input parameters and return values of pointers and functions. In short, const indicates read-only, essentially, it only defines a read-only constant in the global data segment or stack, rather than actually located in the String constant area. Const aims to generate high-quality code, improve code readability, and protect the memory that cannot be changed at will, thus reducing the probability of generating bugs.

Const int A = 10;

Const int B; // error. The constant must be initialized.

Int A = 10, B = 9;

Const int * P1 = & A; // The content pointed to by the pointer is read-only and cannot be written using this pointer

* P1 = 11; // Error

Int * const P2 = & A; // the pointer itself is read-only. After the pointer is initialized to an object, it cannot be modified.

P2 = & B; // Error

Const int* P3Const= &;// The pointer itself and the pointing content are both read-only

 

Const char * FP1 (void) // modifies the returned value, indicating that the returned Pointer Points to the read-only content

{

Char * P = "dddd ";

Return P;

}

Void FP1 (const char * Str)

{

* STR = 4; // Error

Const char * P = STR; // P must be const to accept Str

}

Int _ tmain (INT argc, _ tchar * argv [])

{

Const char * D = FP1 ();

Printf ("% s", d );

}

 

Iii. extern usage: variables defined in other files must be declared with extern to be used in this file, for example, extern; it will be used as a variable defined in this file.

 

Iv. Static usage:

1. modify the variable. It indicates that the variable is located in the data segment no matter whether the static variable is defined inside or outside the function; the access field of the static variable defined in the function external is only the function defined in the file where it is located. Other files cannot be declared and accessed through extern.

2. Modify the function so that the access domain of the function is only visible to the file defined by the function.

3. In the class, variables are modified with static to indicate that the variables are class variables. in the class, functions use static to indicate that the function can only perform static variables in the class. This pointer is not accepted and is called a class function.

For example:

// File1

Void fstatic (void );

Static void fstatic (void)

{

Return;

}

// File2

Void fstatic (void );

Main ()

{

Fstatic (); // The declaration still cannot be called.

}

In short, static implements the encapsulation of C language and information encapsulation and hiding to a certain extent.

 

5. sizeof usage: sizeof is an operator. The compiler can determine the computation result during compilation, the calculation object can be an internal data type name, struct type name, class type name, array variable, and other types of variables. Only when the calculation object is an array variable, the actual length of the array can be obtained. When other types of variables are used as calculation objects, the calculation of the Data Type of the object will be degraded. In addition, when computing user-defined data types such as struct and class, you need to consider that the compiler will optimize it and adjust it according to certain principles, that is, it will automatically align, the result of sizeof is usually greater than the sum of the length of each element.

Example 1:

Short L; // sizeof (L) = 2

Char * A = "abcddd"; // sizeof (A) = 4

Void * s = malloc (100); // sizeof (S) = 4

Char B [] = "abcddd"; // sizeof (B) = 7*1

Float C [20]; // sizeof (c) = 20*4;

Example 2:

Struct

{

Short;

Short B;

Short C;

}; // Sizeof (A) = 6

Struct B

{

Int;

Char B;

Short C;

}; // Sizeof (A) = 8

 

Struct C

{

Double A1;

Long;

Int A2;

Char B;

 

}; // Sizeof (B) = 24

# Pragma pack (1) // use the pack command to force the compiler not to optimize it. This method is generally used for this

Struct D // when the struct needs to be directly written to a file or directly used for sending and receiving through the network

{

Double A1;

Long;

Int A2;

Char B;

 

};

# Pragma pack () // sizeof (B) = 17

Note: Example 2 demonstrates how data is accessed. Because the CPU accesses data by multiple bytes at a time, if the first address of the Multi-byte data is an integer multiple of 2, all the data corresponding to the variable can be obtained after one memory access. Therefore, an optimization requirement is that the variable address is an integer multiple of its data type length, for example, the address of a of int A must be an integer multiple of 4.

For struct, if all elements in the struct are of the same type and are processed as arrays, struct a is input; otherwise, it is generally an integer multiple of the most common elements, such as struct B and C. The purpose of this processing is to define the struct array, for example, struct B [10]; if each of the 10 struct variables is 8, it will ensure that the first element of each variable can be an integer multiple of 4. Otherwise, this effect will not be achieved and efficient memory access will not be achieved, therefore, the compiler automatically adjusts Data Alignment for non-conforming structs.

Finally, the static variables in the class are not allocated to the stack, so they cannot be included in sizeof. The length of the empty class is 1 and the length of a virtual function is 4, it contains a pointer to the function table.

The following are several interview questions:

Example 1:

IntFP1 (CharVaR [])// The return value is 4, because the normal pointer is degraded when VaR is passed as a parameter,

{// Therefore, the pointer size cannot be calculated because it is not processed as an array name.

Return sizeof (VAR );

}

 

 

Example 2:

// Str1 is an array name, which is a pointer array with a length of 3, so sizeof (str1) is 3*4

Void FP1 (void)

{

Char * str1 [] = {"hello", "Mico", "China "};

For (INT I = 0; I <sizeof (str1)/sizeof (char *); I ++)

{

Printf ("% s", str1 [I]);

}

}

 

6. Volatile usage: The term "changeable" is used to modify a keyword of a variable, indicating that the variable can be changed in many places and will be changed by imitations, the compiler cannot optimize it. It is often used in multi-task or embedded systems. Case 1: The values of many peripheral registers in embedded systems change in real time, for example: # define PTA * (volatile unsigned char *) (0x00000001); Case 2: some variables in the memory of the embedded system may be modified by the interrupted program. Case 3: shared variables in a multitasking system may change at any time. Variables that meet one of these characteristics must be modified with volatile to ensure that the compiler cannot optimize them. If optimized, the execution result of the program is often incorrect.

Example 1:

Int A = 10;

If (A = 10)

{

A = 11;

}

The short code is optimized

A = 11; however, if volatile int A; then this code will not be optimized.

Example 2:

// Original code:

Int square (volatile int * PTR)

{

Return * PTR ** PTR;

}

// Code optimized by the compiler:

Int square (volatile int * PTR)

{

Int A = * PTR;

Int B = * PTR;

Return a * B;

}

// Correct code: The * PTR value may change at any time, so the values of A and B in the optimization code may be different.

Int square (volatile int * PTR) // The result may be incorrect.

{

Int A = * PTR;

Return a *;

}

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.