The role of keywords auto, static, register, const, volatile, extern in C language

1.auto

This keyword is used to declare that the lifetime of a variable is automatic, that is, variables not defined in any class, structure, enumeration, union, and function are considered global variables, and variables defined in functions are considered local variables . This keyword is not written much, because all variables are auto by default.

 

 

int func(){
    auto int a;
    return 1;
}
auto int b = 22;
int main(int argc, char const *argv[])
{

    printf("%d\n", b);

    return 0;
}

/*
mainc.c:7:10: error: file-scope declaration of 'b' specifies 'auto'
 auto int b = 22;
*/

 

 2.register 

This keyword instructs the compiler to store variables in CPU internal registers as much as possible instead of accessing them through memory addressing to improve efficiency.

 

int main(int argc, char const *argv[])
{
    register int b = 10;
    printf("%d\n", b);

    printf("%p\n", &b);

    return 0;
}



/*
mainc.c: In function 'main':
mainc.c:13:2: error: address of register variable 'b' requested
  printf("%p\n", &b);
*/

 

 3.static 

    3.1 A static  storage class instructs the compiler to keep a local variable alive for the lifetime of the program without creating and destroying it every time it enters and leaves the scope. Therefore, decorating a local variable with static preserves the value of the local variable between function calls.

    3.2 The static modifier can also be applied to global variables. When static modifies a global variable, it limits the scope of the variable to the file in which it is declared.

    3.3 static is the default storage class for global variables

 

4.external

  4.1 The extern  storage class is used to provide a reference to a global variable, which is visible to all program files. When you use 'extern', for variables that cannot be initialized, the variable name points to a previously defined storage location.

  4.2 When you have multiple files and define a global variable or function that can be used in other files, you can use  extern in other files  to get a reference to the defined variable or function. It can be understood that extern  is used to declare a global variable or function in another file.

    The extern modifier is usually used when two or more files share the same global variable or function

// main.c
#include <stdio.h> int count ; extern void write_extern(); intmain () { count = 5; write_extern(); } // a.c #include <stdio.h> extern int count; void write_extern(void) { printf("count is %d\n", count); }

 

 

 

 Reference: https://www.cnblogs.com/candyming/archive/2011/11/25/2262826.html

        http://www.runoob.com/cprogramming/c-storage-classes.html

 

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325020785&siteId=291194637