C Language Notes (1), C Language notes

Source: Internet
Author: User

C Language Notes (1), C Language notes

Joke:
Programmer A: "Dude, I have been busy recently. Do you want to borrow some money ?"
Programmer B: "How much is it ?"
Programmer A: "One thousand rows ?"
Programmer B: "Who are you talking! I'll give you an integer of 1024. Let's take it ."

====================================== I am a cut-off line ============== ====================

Preface

The C language allows you to directly access the physical address and operate on the hardware. It is very suitable for developing the kernel and hardware driver.

In the book, it seems that the average person has not mastered the C language for three years;

Generally, C language is not familiar in five years.

The most basic thing to learn about a language is multi-code and multi-debugging. If necessary, you can use the yellow duck debugging method.

Think more and try to solve problems in depth.

The following notes are from deep anatomy of C language.

 

Variable

The most important difference between definition and declaration:The definition creates an object and allocates memory for the object. It is declared that no memory is allocated.

 

Common variables use the CamelCase method with the necessary prefix and suffix.
All macro definitions, enumeration constants, and read-only variables are named in uppercase and separated by underscores.

 

There are four Storage types in C language:Auto, extern, register, static, you can only specify one of the types when defining variables.
The variables are allocated in the memory storage space: BSS, Data, stack, and heap.

Structure of processes in memory
  • Code zone: stores the machine commands executed by the CPU. The Code zone can be shared and read-only.
  • BSS: stores uninitialized global and static variables.
  • Data zone: stores initialized global variables, static variables (global and local), and constant data.
  • Stack zone: the stack zone is automatically allocated and released by the compiler. It stores the parameter values, return values, and local variables of the function, and is allocated and released in real time during the program running. The stack zone is automatically managed by the operating system, manual management is not required by programmers.
  • Heap zone: memory blocks allocated by the malloc () function. The free () function is used to release the memory. The application and release of the heap are controlled by the programmer and prone to memory leakage.

Some variables are not in the memory: The register variable may not be stored in the memory, so the address of the register variable cannot be obtained using the "&" operator.

 

Static

The first role is to modify the variable. Static global variables and static local variables both have static memory areas.
Static global variables are limited to the files defined by the variables. Other files cannot be used even if they are declared using extern.
Static local variables defined in the function body can only be used in this function, and other functions in the same document cannot be used.
The second role is to modify the function. It is not a storage method, but a function's scope is limited to this file (so it is also called an internal function ).
The advantage is that different people do not have to worry about their own defined functions when writing different functions, and whether they will have the same name as the functions in other files.

 

Sizeof keywords

Int I = 0;
A), sizeof (int); B), sizeof (I); C), sizeof int; D), sizeof I;

Here, only option C is incorrect, because sizeof can be omitted when the space occupied by the calculation variable is large, but not when the calculation type is large.
In addition, sizeof is not afraid of cross-border address. It only calculates the space occupied by the variable type, does not access the address of the variable, and it is unclear that the storage does not exist.

 

Signed and unsigned keywords

1. What is the output of the following code? Why?

void foo(viod){    unsigned int a = 6;    int b = -20;    (a+b>6)?puts(">6"):puts("<=6");}

 

2. What is the result of the following code? Why?

intmain(){    char a[1000];    inti;    for(i=0; i<1000; i++)    {        a[i] = -1-i;    }    printf("%d",strlen(a));    return 0;}

 

Void literally means "null type", void * is "null type Pointer", void * can point to any type of data.
Any type of pointer can be directly assigned to void *, without the need for forced type conversion:
Void * p1;
Int * p2;
P1 = p2;

 

The value after case can only be a constant or constant expression of the integer or numeric type.

 

Defines the const read-only variable, which is non-mutable. The const modifier is still a variable, but it is a read-only attribute and cannot be used as a constant.
The const modifier can also be used to modify the function parameters. It is used when you do not want this parameter value to be accidentally changed by the function body.

The role of const: saves space, avoids unnecessary memory allocation, and improves efficiency
Generally, the compiler does not allocate storage space for common const Read-Only variables, but stores them in the symbol table, which makes it a value during compilation without the operation of storage and read memory, this makes it highly efficient.

 

Volatile

Volatile variable, the compiler no longer optimizes the code that accesses the variable, so as to provide stable access to the special address.

Let's take a look at the following example:
Inti = 10;
Intj = I; // (1) Statement
Intk = I; // (2) Statement

At this time, the compiler optimizes the code because I is not used as the left value (not assigned) in the (1) and (2) statements ). At this time, the compiler considers that the value of I has not changed. Therefore, after the I value is obtained from the memory in the (1) Statement and assigned to j, this value is not lost, instead, this value is used to assign a value to k in the (2) statement. The compiler does not generate assembly code to retrieve the I value from the memory again, which improves the efficiency.
Note: (1), (2) the I between statements is not used as the left value.

 

Let's look at another example:
Volatile inti = 10;
Intj = I; // (3) Statement
Intk = I; // (4) Statement
The volatile keyword tells the compiler that I may change at any time. Each time you use it, you must retrieve the I value from the memory, therefore, the compilation code generated by the compiler will re-read data from the address of I and put it in k.

When should I use volatile?

If I is a register variable, a port data, or shared data of multiple threads, it is prone to errors. Therefore, volatile can ensure stable access to special addresses.

 

Size-end Mode 3. Confirm the storage mode of the current system?
int checkSystem{    union check    {        int i;        char ch;    }c;    c.i = 1;   return(c.ch == 1);}

If the processor is Big_endian, 0 is returned; if the processor is Little_endian, 1 is returned.

 

Big-end mode (Big_endian): Word dataHigh byteStored inLow addressAnd word dataLow bytesStored inHigh address.
Small-end mode (Little_endian): Word dataHigh byteStored inHigh addressAnd word dataLow bytesStored inLow address.

Union {int I; char a [2];} * p, u; p = & u; p-> a [0] = 0x39; p-> a [1] = 0x38;

The access to members of the union type starts at 0 from the base address of the consortium.

5. In x86 systems, what is the output value of the following program?
#include <stdio.h>int main(void){    int a[5] = {1,2,3,4,5};    int *ptr1 = (int *)(&a + 1);    int *ptr2 = (int *)((int)a + 1);    printf("%x,%x\n",ptr1[-1],*ptr2);    return 0;}

 

Struct 6. What are the differences between the following two sections of code?
// Code (1) structTestStruct1 {char c1; shorts; char c2; inti ;}; // code (2) structTestStruct2 {char c1; char c2; shorts; inti ;};

The value of sizeof (TestStruct1) is 12.

The value of sizeof (TestStruct2) is 8.

Words, dual words, and four words do not need to be aligned in the memory on the natural boundary. (For words, double words, and four words, the natural boundary isEven address, Which can be divided by four, and can be divided by eight .) In any case, to improve program performance,Data structure (especially stack)Align as much as possible on the natural boundary. The reason is that the processor needsTwiceMemory Access; however, alignment memory access only needsOnceAccess.

You can use # pragma pack () to change the default alignment of the compiler:

#pragma pack(n) //n=1,2,4,8,16…

 

Enum
enum Color{    GREEN = 1,    RED,  //2    BLUE, //3    GREEN_RED = 10,    GREEN_BLUE //11}ColorVal;

 

Function At least the function Header
// Function: Change the buffer size // parameter: New length of the nNewSize buffer // return value: current length of the buffer // Description: keep the original information unchanged
Complete Function Description
/************************************************************************ * Function Name             : nucFindThread * Create Date               : 2000/01/07 * Author/Corporation        : your name/your company name * * Description               : Find a proper thread in thread array. *                             If it’s a new then search an empty. * * Param : ThreadNo          : someParam description * ThreadStatus              : someParam description * * Return Code               : Return Code description,eg:                               ERROR_Fail: not find a thread                               ERROR_SUCCEED: found * * Global Variable           : DISP_wuiSegmentAppID * File Static Variable      : naucThreadNo * Function Static Variable  : None * *------------------------------------------------------------------------ *   Revision History *   No.  Date       Revised by  Item  Description *   V0.5 2008/01/07 your name   …     … ************************************************************************/static unsigned char nucFindThread(unsigned char ThreadNo,unsigned char ThreadStatus){    // TODO:...}//Blank Line
Notes for function writing:
  • Protective Programming
  • The indentation should contain 4 characters in length.
  • In a function, empty lines must be added between variable definitions and function statements.
  • The closely related statements on zookeeper do not contain empty lines. Separate empty lines in other places.
  • In complex functions, annotations are required after the branch statement and loop statement are completed to distinguish the branches or loop bodies // end "for (condition )"
  • Use assert macro for function entry check assert (NULL! = P );
  • An error may occur when the recursion depth is too large (for example, Stack Overflow)
  • The return statement cannot return a "Pointer" pointing to "stack memory" because the function body is automatically destroyed when it ends.

 

File

File Name: abbreviated Module name + lowercase letter name

File Header description
/************************************************************************ * File Name           : FN_FileName.c/ FN_FileName.h * Copyright           : 2003-2008 XXXX Corporation,All Rights Reserved. * Module Name         : DrawEngine/Display * * CPU                 : ARM7 * RTOS                : Tron * * Create Date         : 2008/10/01 * Author/Corporation  : WhoAmI/yourcompany name * * AbstractDescription : Place some descriptionhere. * *-----------------------Revision History-------------------------------- * No  Version  Date      Revised By  Item           Description * 1   V0.95    08.05.18  WhoAmI      abcdefghijklm  WhatUDo * ************************************************************************/#ifndef __FN_FILENAME_H#define __FN_FILENAME_H#endif// Debug Switch Section// Include File Section// Macro Define Section// Structure Define Section// Prototype Declare Section// Global Variable Declare Section// File Static Variable Define Section// Function Define Section

 

Subsequent plans:
  • Read the pre-processing Section in modern method (version 2nd)
  • Learning arm Assembly
  • Understand C language at the level of assembly language, C/C ++ deep exploration by Mr Yao xinyan, and X86 assembly

 

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.