MMGameslogo  MMGames
TwitterSharebutton  FacebookSharebutton   
learn through sufferingC Language
learn through sufferingC Language

The last variable standing

Global variable lifetime
In the previous section, we explained that variables declared within a function have a lifetime that ends within that function.
Naturally, that leads one to consider what would happen outside the function.

"I used to declare all variables inside functions, but it turns out you can also declare them outside of functions."
Variables declared outside of a function are sometimes called global variables.

キーワード
【Global variable】

function外で宣言されたvariable。
プログラム全体が終了するまで生き残り続け、
宣言されたSource file内のすべてのfunctionから使用できる。


The following program is an example using global variables.

Source code
#include <stdio.h>

int count; /* Global variable */

int countfunc(void);

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

int countfunc(void)
{
    count++;
    printf("%d\n", count);
    return count;
}

The results of this program's execution are as follows:

Execution results
1
2
3

Unlike the previous chapter, this time the number of function calls is being counted.
This is deeply related to the lifetime of global variables.
Global variables persist for the duration of the program.
Therefore, it remembers previous values even if the variable is called multiple times.

By the way, in the program mentioned above, the variable 'count' was not initialized.
It was neatly output as 1, 2, 3, and that's no coincidence.
Global variables are automatically initialized to zero at the start of the program.

Local variables are created each time a function is called.
"Since it's wasteful to initialize every time, it's not initialized automatically."
Because global variables only need to be initialized once.
shared by all functions
Global variables are variables declared outside of any function.
Unlike local variables within a function, they can be freely used from any function.
The following program demonstrates an example of modifying the variable `count` from the `main` function.

Source code
#include <stdio.h>

int count; /* Global variable */

int countfunc(void);

int main(void)
{
    countfunc();
    count = 10; /* ここで変更 */
    countfunc();
    countfunc();
    return 0;
}

int countfunc(void)
{
    count++;
    printf("%d\n", count);
    return count;
}

The results of this program's execution are as follows:

Execution results
1
11
12

Looking at these results, the value suddenly became 11 on the second display.
This is because the variable 'count' is being modified within the main function.
In this way, global variables are shared by all functions.

"This is convenient because it allows for assignment and value retrieval from any function."
You must use it with great care, paying close attention to how it's used in other functions.
Using global variables heavily can lead to a large number of variable names, which can be very cumbersome.

Therefore, global variables should be used only for data that is meant to be shared throughout the entire program.
Essentially, using local variables can make a program more understandable.
Local variables are independent.
"In the previous section, we explained that global variables are shared by all functions."
If a local variable has the same name as a global variable within a function,
I'd like to experiment to see which takes priority.
"The following program demonstrates declaring a variable named 'count' within the main function."

Source code
#include <stdio.h>

int count; /* Global variable */

int countfunc(void);

int main(void)
{
    int count; /* 同名で宣言 */

    countfunc();
    count = 10;
    countfunc();
    countfunc();
    printf("main : count = %d\n", count);
    return 0;
}

int countfunc(void)
{
    count++;
    printf("%d\n", count);
    return count;
}

The results of this program's execution are as follows:

Execution results
1
2
3
main : count = 10

First, starting with what this program can do,
I understand that you can declare a local variable with the same name as a global variable.

To see which takes priority, let's look at the results.
despite modifying the value of the variable 'count' within the main function,
The numbers within the countfunc function have not been altered at all.
"At the end of the main function, the value assigned within the function is displayed correctly."
In essence, a local variable takes precedence over a global variable if they have the same name.

This is also a mechanism for maintaining the independence of functions, as explained in the previous section.
If global variables are prioritized, when using a copy of a function,
It's a hassle to check if the variables within that function have the same names as global variables.

Source Files and Global Variables
ここではGlobal variableはshared by all functionsとDescriptionしましたが、
正確には、1つのSource file内で共有されています。

たとえば、main.c Fileの先頭で宣言されたGlobal variableは、
main.c File内のすべてのfunctionからAssignmentや値の参照が可能ですが、
別のFile、たとえば data.c Fileのfunctionからは参照できません。

しかし、別のFileにvariableの名前と型を教えてやれば、
Global variableはすべてのFileから使用できるようになります。

複数のSource fileを使う方法はまだDescriptionしていないので、
現段階では、shared by all functionsと考えても違和感ありません。



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. newline character
  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