当前位置:网站首页>You Li takes you to talk about C language 6 (common keywords)

You Li takes you to talk about C language 6 (common keywords)

2022-07-07 07:49:00 Lu Youli

C The language provides a wealth of keywords , And these keywords are predetermined , Users cannot create keywords themselves

 Insert picture description here

Next I will introduce some keywords , Others that are not introduced will be mentioned later

keyword typedey

Can simplify a type , Redefinition

// take unsigned int  Rename it to uint_32,  therefore uint_32 It's also a type name 
typedef unsigned int uint_32;
int main()
{
    
    // Observe num1 and num2, The types of these two variables are the same 
    unsigned int num1 = 0;
    uint_32 num2 = 0;
    return 0; }

keyword static

stay C In language : static Is used to modify variables and functions

  1. Modify local variables - Called static local variables
  2. Modify global variable - Called static global variables
  3. Modify function - Called static function

keyword static – Modify local variables


```c
// Code 1
#include <stdio.h>
void test()
{
    
    int a = 5;
    // Stack area in memory 
    a++;
    printf("%d ", a);
}
// They were destroyed when they went out 
int main()
{
    
 int i = 0;
    for(i=0; i<10; i++)
   {
    
        test();
   }
    return 0; }
//6 6 6 6 6 6 6 6 6 6 


// Code 2
#include <stdio.h>
void test()
{
    
    //static Modify local variables 
    static int a = 5;
    // Stored in the static area of memory 
    a++;
    printf("%d ", a);
}
// It will not be destroyed after going out 
int main()
 {
    
int i = 0;
    for(i=0; i<10; i++)
   {
    
        test();
   }
    return 0;
  }
//6 - 15


Conclusion :
static When modifying local variables , The local variable becomes a static local variable, and the local variable goes out of the local range , Will not destroy , The next entry function still exists
Because :static Modified local variables are stored in the static area

static When modifying a local variable , What actually changes is the storage location of the variable , Originally, a local variable is placed in the stack area , By static After modification, it is placed in the static area .
As a result, the scope still exists , The life cycle doesn't end

keyword static – Modify global variable

static The function of modifier function :
A function originally has external link properties , But be static After modification , The external link attribute becomes the internal link attribute , At this time, this function can only be used inside its own source file , Other files cannot be used .
The scope becomes smaller

// Code 1
//add.c
int g_val = 2022;
//test.c
int main()
{
    
    printf("%d\n", g_val);
    return 0; }
// Code 2
//add.c
static int g_val = 2022;
//test.c
int main()
{
    
    printf("%d\n", g_val);
    return 0; }
原网站

版权声明
本文为[Lu Youli]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202130649033833.html