C block level variables Variables defined inside a block of code

Mondo Technology Updated on 2024-01-31

The so-called ** block, is made ofSurrounded by **. Blocks can be found everywhere in the C language, such as function bodies, selection structures, loop structures, etc. C programs that don't contain chunks can't run at all, and even the simplest C programs (shown in the previous section) do.

C allows you to define variables inside a block, which has a block-level scope;In other words, variables defined inside the block can only be used inside the block, and are invalid when the block is out.

Now that we've talked about functions, the variables that are defined inside a function are called local variables, and we'll move on to the selection structure and loop structure.

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

#include 

Function declarations. int gcd(int a, int b);You can also write int gcd(int, int);

int main().

int n = 40;Number

printf("block n: %d", n);

printf("main n: %d", n);

return 0;

Running Results:

block n: 40

main n: 22

There are two n's here, which are in different scopes and don't create naming conflicts. The scope is smaller than main(), and the internal printf() uses the numbered n, and the internal printf() inside main() uses the numbered n.

Each C program contains multiple scopes, and variables with the same name can appear in different scopes, and C will search for variables in the parent scope in order from smallest to largest, layer by layer, and if the variable has not been found in the topmost global scope, then an error will be reported.

Let's demonstrate with a specific **:

#include 

int m = 13;

int n = 10;

void func1(){

int n = 20;

int n = 822;

printf("block1 n: %d", n);

printf("func1 n: %d", n);

void func2(int n){

for(int i=0; i<10; i++)

if(i % 5 == 0){

printf("if m: %d", m);

else{int n = i % 4;

if(n<2 &&n>0){

printf("else m: %d", m);

printf("func2 n: %d", n);

void func3(){

printf("func3 n: %d", n);

int main(){

int n = 30;

func1();

func2(n);

func3();

printf("main n: %d", n);

return 0;

The following diagram illustrates the scope of this section:

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

That's all for this time

Related Pages