C scope

I will explain the scope of C language.

Scope of local variables

First, about the scope of local variables. The scope of local variables is defined inside the function.

Blocks scope local variables

The scope of local variables is created by blocks. Think of a block as the part closed by the "{" and "}" used inside the function.

// Function blocks create scope
void foo (void) {
  
  // If minutes block creates scope
  if (1) {
    
  }
  
  // The block of the while statement creates a scope
  for (condition) {
    
  }

  // The block of the while statement creates a scope
  while (1) {
    
  }
  
  // The switch statement block creates a scope
  switch (condition) {
    case 1:
      break;
    case 2:
      break;
  }
  
  // Only blocks are OK
  {
    1;
  }
}

How local variables look

Local variables can be defined for each scope. If you can't find a local variable in your scope, go look for a local variable in the next higher scope. Repeat below. If you can't find a local variable, you'll go looking for a global variable with file scope, and if you can't find it, you'll go looking for a global variable, which we'll discuss later.

#include <stdio.h>
#include <stdint.h>

int main (void) {
  int32_t num1 = 11;
  int32_t num2 = 12;
  int32_t num3 = 13;

  printf("[SCOPE1] num1:%d, num2:%d, num3:%d\n", num1, num2, num3);
  
  if (1) {
    int32_t num1 = 21;
    int32_t num2 = 22;

    printf("[SCOPE2] num1:%d, num2:%d, num3:%d\n", num1, num2, num3);
    
    {
      int32_t num1 = 31;
      
      printf("[SCOPE3] num1:%d, num2:%d, num3:%d\n", num1, num2, num3);
    }
  }
}

This is the output result. Take a closer look at where you can see the declared variables.

[SCOPE1] num1: 11, num2: 12, num3: 13
[SCOPE2] num1: 21, num2: 22, num3: 13
[SCOPE3] num1: 31, num2: 22, num3: 13

Associated Information