Reading notes-C language keywords

Source: Internet
Author: User
Tags case statement modifier switch case volatile

001 Key Words
    • C language altogether 32 keywords 1. Declarations and definitions
    • Before you begin to recognize a keyword, you must understand what a statement is and what defines it:
      • Definition: (compiler) Creates an object, allocates a memory for the object, and gives him a name. Within a scope, a variable or object can only be defined once, and the memory allocated for it will be immutable;
      • Declaration: 1, tell the compiler that the name has been matched with a piece of memory, and this memory is defined elsewhere, the declaration can be multiple times; 2, tell the compiler that the name is already occupied and can no longer be used to define other variables or objects.
    • Note: The definition creates an object and allocates memory for it, declaring no memory allocated
2. Keyword 2.1. Auto (the most magnanimous keyword)
    • By default, all the variables in the compiler default are auto, so we can do this when it doesn't exist.
2.2. Register (fastest keyword)
    • Request compiler, as far as possible to use the variables defined by the register to the CPU register, not guaranteed to put. (CPU registers are limited)
    • NOTE: Register variable length should be less than or equal to int and cannot use & (register variable is not stored in memory)
2.3. Static (most inconsistent keywords)
    • Modifier variables
      • Modifies global variables, from the start of the definition to the end of the file, other files cannot be used even if extern is used
      • Modifies local variables, which can only be used inside the function body
      • Because the static modified variable is stored in the memory of the quiescent zone, so even if the function is finished, the variable will not be destroyed, the function can use this value the next time.
    • Modifier functions
      • The function uses the static decoration to indicate that the scope is limited to this file, also called the intrinsic function
2.4. Short, int, long, char, float, double (base data type)

    • Naming rules for variables
      • Min length && max information
      • Hope and know, easy to remember
      • Consists of multiple words, either underlined or capitalized in the first letter of each word
      • Try to avoid numeric numbering unless you logically need to
      • All macro definitions, enumeration constants, read-only variables are all capitalized, and the words are split with underscores
      • Cyclic variables n, m, I, J, K;char C; int a[]; int *p.
2.5. sizeof (the most wronged keyword)
    • sizeof is one of the 32 keywords, not a function.
    • what does sizeof (int) * p mean?
2.6. Signed unsigned keywords
    • First to analyze a piece of code
#include <stdio.h>#include <string.h>int main(){    signed char a[1000];    int i = 0;    for (i = 0; i < 1000; i++)    {        a[i] = -1 - i;    }    printf("%d\n", strlen(a));    return 0;}

When i = 128, a[128] = -1-128 = -129, signed char range is -128~127, so out of range, -129 Source: 1 1000 0001, complement: 1 0111 1111, low 8-bit 01 11 1111, or 127.

When i = 255, a[255] = 1-255 =-256, 256 of the original code 11 0000 0000 Complement: 11 0000 0000, Low 8 bits are all 0, strlen encounters ' "" to end, so the above code output 255 。

Therefore, the char type is used to represent the character if used directly, and if the signed and unsigned qualifiers are added, the numbers are represented.

2.7. If Else combination
    • The bool variable is compared to the "0 value"
bool b = FALSE;if(b)    printf("TRUE");if(!b)    printf("FALSE");

The above writing is recommended, other ways will be problematic.

    • The float variable is compared to the "0 value"
      if(test > -EPSINON) || (test < EPSINON); // EPSINON 为定义好的精度
    • Pointer variable compared to "0 value"
      if(NULL == p)if(NULL != p)
    • Deal with the abnormal situation after the normal situation or the first processing probability is large, the processing probability is small
    • Assignment operations cannot be used to produce bool-worthy expressions
      if((x = y) != 0 )printf("------");

      It's wrong to write like this.

      x = y;if(x != 0)printf("-----");
2.8. Switch case Combination

The If else combination can be used when nesting a small number of branches, but it is necessary to use the switch case combination when there are many nested branches, but do not deliberately create a switch variable.

    • Do not forget the break at the end of each case; Unless you intentionally make multiple branches coincident.
    • The default branch must be used at the end, and a break is required.
    • The return statement is not allowed in the switch case combination.
    • The switch expression should not be a valid bool value, for example, the following expression is not allowed.
      switch (x == 0){......}
    • The value after the case can only be a constant or constant expression of type XXX or character.
    • The order in which case statements are taken
      • In alphabetical order
      • Put the normal situation in front, put the exception in the back, and do a good job of commenting, where is the beginning, where is the end.
      • Put the usual implementation in front of the situation, and the infrequently executed case is behind.
    • There are no cases where the relevant code is as concise as possible, and functions can be used if necessary.
2.9. Do and for keyword
    • The difference between break and continue
      • Break jumps out of the loop
      • Continue terminates this cycle and enters the next cycle
    • Multiple loops should be the longest cycle in the most internal layer, the shortest loop on the outermost, which can effectively reduce the number of cycles of the CPU switching cycle layer.
    • In the For loop, the half open interval is more intuitive than the closed interval and can be written as a < 10, never written as a <= 9.
    • Do not change the loop variable in the for loop, or it will cause the loop to get out of control, like the following code is not good.
      for(int i = 0; i < n; i++){n = 10;}
    • Loop nesting control is within 3 levels.
    • The control statement for the For loop cannot contain variables of any floating-point type.
2.10. Goto keyword

goto keyword can be flexible in the code to jump, there is a lot of controversy, and some of the recommendations are cautious to use Goto, some suggestions do not use. I think the use is good or can be used.

int *p = NULL;...goto error;...error:    return -1;
2.11. void keyword
void *p = NULL;int *p_int = NULL;p = p_int;    //不会报错,是正确的p_int = p;    //报错,是错误的
    • void modifier function return value and function parameter
      • If a function does not have a return value that should be declared as void type, the function has no arguments and should declare it as void type
      • Declared void if the argument to a function can be any type of pointer
        void *memcpy(void *dest, const void *src, size_t len)
    • Void cannot represent a real variable, for example, the following code is wrong
      void a;fun(void a);
2.12. return keyword
    • Return is used to terminate a function and return the value followed by it.
      return(value);    //括号可以省略,但一般不省略,尤其是返回一个表达式的值得时候
    • Return cannot return a pointer to the stack memory because the memory was destroyed at the end of the function body.
2.13. const keyword
    • Const-Modified read-only variables must be initialized in the defined colleague (first const-modified variables, followed by read-only, two-tier meanings)
    • Think of a switch case that could be a const-modified read-only variable after the case statement?

Ignore the type first, see the const who is near to modify who

const int *p;           // const *p ,修饰 *p , p 可以改变, p 指向的内容不可变int const *p;           // const *p ,同上int * const p;          // * const p ,修饰 p,p 不可以改变,p 指向的内容可以改变const int * const p;    // const * const p ,第一个 const 修饰 *p,第二个 const 修饰 p,所以 p 和 p 指向的内容都不能改变
    • The parameters of the modifier function, which can be used when you do not want the parameters of the function to be changed in the body of the function.
    • The return value of the modifier function (const int fun (void)).
    • use extern const int I when another file references a const variable; Declarations can be, not defined.
2.14. Volatile most volatile keywords
    • The volatile keyword, like const, is a type modifier. Its modified variable representation can be changed by factors unknown to the compiler, such as the operating system, hardware, or other threads. When you encounter this keyword-modified variable, the compiler does not optimize it and re-reads it every time it needs to be accessed.

Here the volatile just tells the compiler that the value of a may be changed and needs to be accessed every time you need to go back in memory.

2.15. extern The most hat-wearing keyword
    • modifier functions and variables, which represent functions and variables that are not defined in this file, only use the extern declaration in this file.
2.16. struct keyword

How much memory does an empty structure account for? Most compilers are 1,GCC is 0. So don't be too sure about what's on the books, so be sure to verify it yourself.

    • Flexible arrays
      • Do not be surprised, C language does have a flexible array of this argument.
      • In C99, the last member of the struct allows an array of unknown size, which is a flexible array. However, a flexible array member must have at least one other member before it. sizeof calculates a size that does not contain the space occupied by a flexible array. Allocates memory for the struct containing the flexible array to use malloc, and the allocated memory should be greater than the value calculated by sizeof.
typedef struct st_type{    int i;    a[0];}type_a;//有些编译器会报错,可以改成typedef struct st_type{    int i;    int a[];}type_a;
//可以使用下面的代码为柔性数组分配内存,但是分配好之后使用 sizeof 计算结构体的大小依然是不包含柔性数组所占的内存的。type_a *p = (type_a *)malloc(sizeof(type_a) + 100 * sizeof(int));//记得用完之后要 freefree(p);
    • Can a function be placed inside a struct?

2.17. Union keyword
    • All data members in the Union share a piece of memory, and only one of the data members can be stored at the same time. The size of the union is the size of the memory that the largest member occupies. 2.17.1. Effect of the size end on the Union type data
union {        int i;        char ch;}c;c.i = 1;//这时候 ch 只需要一个字节存储,在低地址,如果 ch 的值等于 1, 说明 i 的值得低字节 1 存储在低地址,是小端模式。Ubuntu、Windows 等 x86 架构都是小端模式。
int main(){    int a[5] = { 1, 2, 3, 4, 5 };    int *p1 = (int *)(&a + 1);    int *p2 = (int *)((int)a + 1);    printf("%x %x\n", p1[-1], *p2);    return 0;}// 5 2000000 小端模式 大端模式 5 2
2.18. Enum keyword
enum enum_type_name{    ENUM_CONST_1,    ENUM_CONST_2,    ENUM_CONST_3,    ...    ENUM_CONST_n} enum_variable_name;
    • Enum_type_name is a custom enumeration type, and Enum_variable_name is a variable of type Enum_type_name.
    • What is the value of sizeof (Enum_variable_name)? Consider the type of the enumeration member to know that it is 4, and the size of the empty enumeration type is also 4.
2.19. typedef keyword, the greatest sewing artist
    • A typedef is an alias for an already existing data type, rather than redefining the new data type.
typedef struct student{    int age;    char name;} stu_1, *stu_2;const stu_2 student_1;    // 其实是 const (struct student *)student_1; 所以 修饰的是 student_1 本身,而不是指向的内容stu_2 const student_2;    // 其实是 (struct student *)const student_2; 所以 修饰的也是 student_2 这个指针本身,而不是指向的内容
    • The difference between a typedef and a #define
#defien INT32 inttypedef int INT32_tunsigned INT32 i = 10;    //没问题,只是替换unsigned INT32_t j = 10;  //错误,不支持#defien PCHAR char*typedef char* pcharPCHAR ch1, ch2;    //ch1 是 char * 类型,ch2 却是 char 类型pchar ch2, ch4;    //ch3, ch4 都是 char * 类型

3. Summary

Do not review do not know, a review startled, the original C language keyword also has so many knowledge points, before also did not pay attention to, of course, not only these, I just recorded I think more important and easy to confuse.

If you think my reading notes are useful for you, you can pay attention to the public number Kalier Oh, the latest articles and reading notes will start here.

Reading notes-C language keywords

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.