C language block level variables

Posted by pneudralics on Mon, 24 Feb 2020 07:37:31 +0100

Code block is the code surrounded by {}. Code block can be seen everywhere in C language, such as function body, selection structure, loop structure, etc. C language programs that do not contain code blocks cannot run at all. Even the simplest c language programs must contain code blocks.

C language allows defining variables within a code block, which has block level scope; in other words, variables defined within a code block can only be used within a code block, and the code block is invalid.

Example 1 defines a function gcd() to find the greatest common divisor of two integers.

#include <stdio.h>

//Function declaration
int gcd(int a, int b);  //You can also write int gcd(int, int);

int main(){
    printf("The greatest common divisor is %d\n", gcd(100, 60));
    return 0;
}

//Function definition
int gcd(int a, int b){
    //If a < B, then exchange the values of the two variables
    if(a < b){
        int temp1 = a;  //Block level variable
        a = b;
        b = temp1;
    }
   
    //greatest common factor 
    while(b!=0){
        int temp2 = b;  //Block level variable
        b = a % b;
        a = temp2;
    }
   
    return a;
}

Operation result:

The greatest common divisor is 20

We only need to pay attention to two variables, temp1 and temp2, which are block level variables defined inside the code block. The scope of temp1 is inside if, and the scope of temp2 is inside while.

Defining variables in for loop conditions

New variables are defined in the for loop conditions. Such variables are also block level variables. Their scope is limited to the internal of the for loop. For example, calculate the sum of the sum from m to n:

#include <stdio.h>

int sum(int m, int n);

int main(){
    printf("The sum from 1 to 100 is %d\n", sum(1, 100));
    return 0;
}

int sum(int m, int n){
    int sum = 0;
    for(int i=m; i<=n; i++){  //i is a block level variable
        sum += i;
    }
    return sum;
}

Variable i is defined in the loop condition, so it is a block level variable. Its scope is the current for loop, and the for loop is invalid.

If a variable is only used inside the for loop, it can be defined in the loop condition, so as to avoid defining too many variables at the beginning of the function and make the code structure clearer.

Instance 2 defines a function, strchar(), to see if the given character is in a string.

#include <stdio.h>
#include <string.h>

int strchar(char *str, char c);

int main(){
    char url[] = "http://www.baidu.com";
    char letter = 'c';
    if(strchar(url, letter) >= 0){
        printf("The letter is in the string.\n");
    }else{
        printf("The letter is not in the string.\n");
    }
    return 0;
}

int strchar(char *str, char c){
    for(int i=0,len=strlen(str); i<len; i++){  //i and len are block level variables
        if(str[i] == c){
            return i;
        }
    }
   
    return -1;
}

One or more variables can be defined in the loop condition. In this code, we have defined two variables, i and len, which are block level variables with the scope of the current for loop.

Separate code blocks

C also allows separate code blocks, which are also a scope.

Example

#include <stdio.h>
int main(){
    int n = 22;  //Number 1
    //Code block surrounded by {}
    {
        int n = 40;  //Number 2
        printf("block n: %d\n", n);
    }
    printf("main n: %d\n", n);
   
    return 0;
}

Operation result:

block n: 40
main n: 22

There are two n's that are in different scopes and do not produce naming conflicts. The scope of {} is smaller than that of main(). printf() inside {} uses n numbered ②, and printf() inside main() uses n numbered ①.

Scope of action

Each C language program contains multiple scopes. Variables with the same name can appear in different scopes. C language will search for variables in the parent scope layer by layer in the order of small to large. If this variable is not found in the top-level global scope, an error will be reported.

Specific code

#include <stdio.h>

int m = 13;
int n = 10;

void func1(){
    int n = 20;
    {
        int n = 822;
        printf("block1 n: %d\n", n);
    }
    printf("func1 n: %d\n", n);
}

void func2(int n){
    for(int i=0; i<10; i++){
        if(i % 5 == 0){
            printf("if m: %d\n", m);
        }else{
            int n = i % 4;
            if(n<2 && n>0){
                printf("else m: %d\n", m);
            }
        }
    }
    printf("func2 n: %d\n", n);
}

void func3(){
    printf("func3 n: %d\n", n);
}

int main(){
    int n = 30;
    func1();
    func2(n);
    func3();
    printf("main n: %d\n", n);
   
    return 0;
}

The following figure shows the scope of this Code:

Blue indicates the name of the scope, red indicates the variables in the scope, and global indicates the global scope. In the scope of gray background, we use the m variable, which is located in the global scope, so we have to go through several scopes to find m.

If you feel good, please like it!!!

326 original articles published, 91 praised, 10000 visitors+
Private letter follow

Topics: C