learn through suffering C language learn through suffering 
C language

Variables with limited scope

Scope of Local Variables

In the previous chapter, we explained functions, but we didn't explain the relationship between functions and variables.
Here, we will create a count function and use it to explain the relationship between functions and variables.
A counter function is a function that counts the number of times it has been called.
There isn't a specific term for it, but we're calling it that for convenience.

Simply put, it can be achieved quite easily.
It's simply a matter of initializing a variable and incrementing it by one each time.
The following program is an example that directly implements the above concept.

Source code
#include <stdio.h>

int countfunc(void);

int main(void)
{
    countfunc();
    countfunc();
    countfunc();
    return 0;
}

int countfunc(void)
{
    int count = 0; /* Initialization */
    count++;
    printf("%d\n", count);
    return count;
}

The results of this program are as follows:

Results
1
1
1

I should have called the function that adds 1 to the variable 'count' three times, but the results are all 1.
It might be caused by assigning 0 during the initialization.

So, I'm going to boldly ignore the warning and try using a variable without initializing it.
In this case, we don't know what number will come up initially.
Even so, the second call should appear one more than the first, and the third should appear two more.
The following program is an example of failing to initialize the variable count.

Source code
#include <stdio.h>

int countfunc(void);

int main(void)
{
    countfunc();
    countfunc();
    countfunc();
    return 0;
}

int countfunc(void)
{
    int count; /* No initialization (You really shouldn't do this) */
    count++;
    printf("%d\n", count);
    return count;
}

The results of running this program were as follows (in my environment).

Results
5369
5369
5369

For some reason, the second and third numbers resulted in the exact same result.
It appears the added amount isn't reflected at all.
This is deeply related to the lifetime of variables.
Actually, variables declared inside a function are discarded when the function ends.
If the same function is called again, we will re-create the variable again.
At this time, a different memory location is being used than before, so the value will also change.

In the previous case, it seems that when I ran it in my environment, I happened to get the same value.
This, ultimately, is entirely a product of chance, and there's no guarantee that the same value will appear.

Essentially, the lifetime of variables declared within the function is limited to the function itself.
In this way, variables that expire within a function are called local variables.
We also sometimes refer to the scope, which encompasses factors such as variable lifetime and validity range.

Keyword
怐Local variable怑

Variables declared within a function. This also applies to formal parameter variables. They are discarded when the function ends, and are newly created when the function is called again. Additionally, they cannot be used from other functions.


Keyword
怐Scope怑

A general term for mechanisms that restrict the scope in which an identifier is valid.
Generally, mechanisms that determine a variable's lifetime and scope.

Variables with the same name but different scopes.

If local variables are discarded when a function ends,
If you declare it in the main function, it should survive until the main function ends.
The following program is an example of declaring the count variable in the main function as well.

Source code
#include <stdio.h>

int countfunc(void);

int main(void)
{
    int count = 0;
    countfunc();
    countfunc();
    countfunc();
    return 0;
}

int countfunc(void)
{
    int count; /* No initialization (You really shouldn't do this) */
    count++;
    printf("%d\n", count);
    return count;
}

The results of running this program were as follows (in my environment).

Results
5369
5369
5369

Despite declaring the count variable in the main function, the result remains the same.
Moreover, even though the count variable is being set to 0 in the main function,
Considering that the countfunc function displays a completely different value,
It seems that variables declared in the main function cannot be used in other functions.

This is closely related to variable scope.
Local variables are only valid within the function they are declared in.
Even if a variable with the same name is declared in another function, it is considered a different variable.
Therefore, changing the value of a variable within the main function will not affect variables in other functions.

Functional independence

So far, we've seen that variables are created completely separately for each function.
The reason for this system is...
The reason is to enhance the independence of the function.

In the previous chapter, we created a sum function to find the sum of min~max, but
This function is readily usable in other programs.
To make functions easily usable, each function needs to be independent.

For example, the sum function used a variable named num.
If all functions were designed to share variables.
If the num variable is used in other functions, its value will be changed.
Therefore, when using the sum function in other programs,
We must thoroughly check for any existing variables with the same name beforehand.

However, if the variables used in each function are independent,
You don't have to worry about affecting the variables of other functions.
You are freed from the fear of sudden variable changes.

Depending on the programming language
C is also a fairly old programming language, but
among even older languages, there are some that don't have variable lifetimes.

In such languages, you must pay careful attention throughout the entire program
to prevent variable values from being modified arbitrarily somewhere.

Therefore, when writing large programs,
you needed an enormous number of variable names for differentiation, which was extremely cumbersome.

Precisely within the block.

Previously, we described the lifetime of local variables as being within a function, but more precisely, it's within a block.
As I explained previously, a block refers to the section of code enclosed in curly braces {}.
So far, it has been used with if statements and for loops.
You can also use only blocks within a function, regardless of those statements.

Source code
#include <stdio.h>

int main(void)
{
    int value1 = 10;
    int value2 = 20;
    
    printf("1:value1 %d\n", value1);
    printf("1:value2 %d\n", value2);

    {
        int value1;
        value1 = 30;
        value2 = 40;
        printf("2:value1 %d\n", value1);
        printf("2:value2 %d\n", value2);
    }

    printf("3:value1 %d\n", value1);
    printf("3:value2 %d\n", value2);

    return 0;
}

The results of this program are as follows:

Results
1:value1 10
1:value2 20
2:value1 30
2:value2 40
3:value1 10
3:value2 40

There are two key points.
One is a deliberately created second block, which allows for the declaration of value1 again.
And it's being treated as a separate variable.
It's clear from the fact that value1 was 30 the second time, but becomes 10 when the block is exited.

Another is the ability to use value2 within intentionally created blocks.
value2 is blocked and the changes remain visible in the third display.

If statements and for loops also have the same behavior because their curly braces {} define blocks.


About This Site

Learning C language through suffering (Kushi C) is
This is the definitive introduction to the C language.
It systematically explains the basic functions of the C language.
The quality is equal to or higher than commercially available books.


Part 0: Program Overview

  1. What is a program?



Chapter 3: Displaying on the Screen

  1. String Display
  2. line break
  3. Practice Problem 3

Chapter 4: Displaying and Calculating Numbers

  1. Display of numbers
  2. Basic calculations
  3. Numeric types
  4. Practice Problem 4


Chapter 6: Input from the Keyboard

  1. input function
  2. The fear of input
  3. Practice Problem 6



Chapter 9: Repeating a Fixed Number of Times

  1. Iterative sentence
  2. How Loops Work
  3. Practice Problem 9

Chapter 10: Repeating Without Knowing the Number of Times

  1. Unspecified loop
  2. Input validation
  3. Practice Problem 10



Chapter 13: Handling Multiple Variables at Once

  1. Handling multiple variables collectively.
  2. Arrays
  3. Practice Problem 13






Chapter 19: Dynamic Arrays

  1. Create arrays freely.
  2. Practice Problem 19

Loading comment system...