C Language Notes (i)

Source: Internet
Author: User

A joke:
Programmer A: "Buddy, have you got a little money on hand recently?" ”
Programmer B: "Come on, how much?" ”
Programmer A: "1000 lines?" ”
Programmer B: "Who and who we are!" Give you a whole, 1024, take it. ”

========================= I'm a split line =========================

Objective

The C language allows direct access to physical addresses and can operate directly on the hardware, making it ideal for developing kernel and hardware drivers.

The book appears a sentence: ordinary people in C language under 3 years, generally speaking, has not mastered C language;

Under 5 years, generally not familiar with C language, under the 10, not proficient.

Learn a language the most basic or more code, more debugging, when necessary, you can use the small yellow Duck debugging method.

Think more, encounter problems and try to study and solve them first.

The following notes are from the "C Language deep Anatomy"

Variable

define and declare the most important difference: The definition creates an object and allocates memory for the object, declaring that no memory is allocated.

The general variables use the Hump naming method (CamelCase), plus the necessary prefix.
All macro definitions, enumeration constants, read-only variables are all capitalized, and the words are split with underscores.

There are 4 types of storage in C:auto, extern, register, Static, and only one of these types can be specified when defining a variable.
The variables are allocated in memory storage space: BSS, data area, stack area, heap area.

The structure of the process in memory
    • Code area: A machine instruction that holds CPU execution, the code area is shareable, and is read-only.
    • BSS: An uninitialized global variable and a static variable are stored.
    • Data area: Holds initialized global variables, static variables (global and local), constant data.
    • Stack area: Automatically allocated by the compiler release, storing the function parameter value, return value and local variables, in the process of running the program in real-time allocation and release, the stack is automatically managed by the operating system, without the programmer manual management.
    • Heap area: A block of memory allocated by the malloc () function that frees memory with the free () function, and the heap's request to release work is controlled by the programmer and prone to memory leaks.

There are also variables that are not in memory: The register variable may not be stored in memory, so the address of the register variable cannot be obtained with the fetch operator "&".

2 Effects of static

The first effect: a modifier variable. Static global variables and static local variables exist in the static area of memory.
Static global variables, scoped only to the file defined by the variable, and other files that use the Extern declaration are not able to use him.
Static local variables, defined within the function body, can only be used in this function, and other functions in the same document cannot be used.
Second effect: modifier function. Instead of storage, it means that the scope of the function is limited to this file (and hence the intrinsic function).
The advantage is that when different people write different functions, they don't have to worry about the functions they define, and whether they have the same name as the functions in other files.

sizeof keyword

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

Only option C here is wrong, because sizeof can omit the parentheses when calculating the space size of the variable, and the parentheses cannot be omitted when calculating the type size .
There is also sizeof not afraid of address out of bounds, it only calculates the variable type occupies the space size, does not go to the address of the variable, it is not clear that there is no existence.

Signed, unsigned keywords

1. What is the following code output? Why?

void foo (viod) {    int6;     int b =-;    (A+b>6) puts (">6"):p UTS ("<=6 " );}

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

Intmain () {    char a[+];    Inti;      for (i=0; i<; i++)    {        =-1-i;    }    printf ("%d", Strlen (a));     return 0 ;}

void literal means "null type", void * is "null type pointer", void * can point to any type of data.
Pointers of any type can be assigned directly to void * Without forcing type conversions:
void *p1;
int *p2;
P1 = p2;

The value following the case can only be a constant or constant expression of an integer or character type.

Defines a const read-only variable with immutability. The const modifier is still a variable, just a read-only property and cannot be used as a constant.
The const modifier can also be used to modify the parameters of a function when it is not desirable that the parameter value be changed unexpectedly by the function body.

The role of const: Save space, avoid unnecessary memory allocations, and improve efficiency
The compiler typically does not allocate storage space for ordinary const read-only variables, but instead saves them in the symbol table, which makes it a compile-time value, without the memory and read operations, making it highly efficient.

Volatile

Volatile modified variables, the compiler does not optimize the code that accesses the variable, thus providing 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

This time the compiler optimizes the code because in the (1), (2) Two statements, I isnot used as an lvalue (not assigned). At this time the compiler thought that the value of I did not change, so when I was removed from memory at the (1) statement, the value was not discarded, but the value was assigned to K at the (2) statement. The compiler does not generate the assembly code to re-fetch the value of I from memory, which improves efficiency.
Note, however, that between (1) and (2) statements I is not used as an lvalue.

Let's look at another example:
Volatile inti=10;
INTJ = i;//(3) statement
INTK = i;//(4) statement
The volatile keyword tells the compiler i is ready to change, and each time it is used it must take the value of I from memory , so the compiler generated assembly code will re-read the data from the address of I in K.

When do you want to use volatile?

If I is a register variable or represents a port data or shared data of multiple threads , it is prone to error, so volatile can guarantee stable access to special addresses.

Size-End Mode 3. Confirm the current system's storage mode?
int checksystem{    Union check    {        int  i;         Char ch;    } C;     1 ;    return 1 );}

Returns 0 if the processor is Big_endian, or 1 if Little_endian.

Big-endian mode (Big_endian): The high byte of the character data is stored in the low address , while the low byte of the word data is placed in the high address .
Small end Mode (Little_endian): The high byte of the character data is stored in the high address , while the low byte of the word data is stored in the low address .

Baidu Encyclopedia:
At present, Intel's 80x86 series chip is the only chip that still insists on using the small end, and the chips such as MIPS and ARM are either stored in a full-endian way, or the option supports switching between the size and the end.
In addition, for the processing of the size side and compiler implementation, in the C language, the default is small (but in some of the implementation of the microcontroller is based on big-endian, such as Keil C51), Java is platform-independent, the default is the large end. Transmitting data over a network is generally a big-endian use.

What is the value of 4.p->i?
union{    int  i;     Char a[2];} *= &u;p->a[00x39;p->a[10x38 ;

The members of the Union are accessed at an offset of 0 relative to the base site of the consortium.

5. Under the x86 system, what is the output value of the following program?
#include <stdio.h>intMainvoid){    inta[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 structs 6. What is the difference between the following 2 sections of code?
// Code (1) structteststruct1{    char  C1;    Shorts;     Char C2;    Inti;}; // Code (2) structteststruct2{    char  C1;     Char C2;    Shorts;    Inti;};

sizeof (TESTSTRUCT1) has a value of 12

sizeof (TESTSTRUCT2) has a value of 8

Word, double word, and four words do not need to be aligned in memory on natural boundaries. (for words, double words, and four words, the natural boundary is an even address , an address that can be divisible by 4, and an address divisible by 8.) In any case, in order to improve the performance of the program, the data structure (especially the stack) should be aligned as far as possible on the natural boundary. The reason is that, in order to access unaligned memory, the processor needs to make two memory accesses; However, aligned memory access requires only one access.

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

#pragma // n=1,2,4,8,16 ...

Enum type enum
enum color{    1,    RED,  //2    BLUE,//3    ,    Green_blue//11}colorval;

Function At least the function head
//   Energy: Change buffer size //  parameter  : nnewsize buffer New length //  return value: Buffer current length / / stating  : Keep the original information content unchanged
Complete description of the function
/** Function Name:nucfindthread * Crea               Te 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:NAUCTH   Readno * Function Static variable:none * *------------------------------------------------------------------------*  Revision History * No. Date revised by Item Description * V0.5 2008/01/07 your name ... ***************************************** ****************************** */StaticUnsignedCharNucfindthread (unsignedCharthreadno,unsignedCharthreadstatus) {    //TODO: ...}//Blank Line
Some notes on function writing:
    • Protective programming
    • Indent uniformly using 4 characters
    • In a function body, a blank line is added between a variable definition and a function statement
    • There is no blank line between the closely related statements on the IBO, and the other places should be separated by a blank line.
    • Complex function, in the branch statement, the Loop statement after the end of the need for appropriate comments, convenient to distinguish between the branches or the loop body//end "for (condition)"
    • Use the Assert macro to do a function entry check assert (NULL! = p);
    • Recursion depth is too large to be error (e.g. stack overflow)
    • The return statement cannot return a pointer to "stack memory" because the memory is automatically destroyed at the end of the function body

File

File naming: module name abbreviation + lowercase letter Name

File Header Description
/************************************************************************ * File name:fn_filename.c/fn_file Name.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--------------------------------* 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

After the plan:
    • Read the section on preprocessing in the Modern Method (2nd edition)
    • Learn arm Compilation
    • From the level of assembly language to understand C language, Yao Yan's "C Language: Standards and implementation", "C + + Deep Exploration", about X86 compilation

C Language Notes (i)

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.