In C++, there are different types of variables that offer various features and behaviors. Let's explore three common types: `const`, `static`, and global variables.
1. `const` Variables:
- A `const` variable is a read-only variable whose value cannot be changed once it is assigned.
- It is declared using the `const` keyword.
- `const` variables must be initialized at the time of declaration.
Here's an example:
const int MAX_VALUE = 100;
In this example, `MAX_VALUE` is a `const` variable with a value of 100. Its value cannot be modified throughout the program.
2. `static` Variables:
- A `static` variable is a variable that retains its value even after its scope or lifetime ends.
- It is declared using the `static` keyword.
- `static` variables have a single shared instance across multiple function calls.
- `static` variables are commonly used for maintaining state or counting instances in functions.
Here's an example:
void countCalls()
{
static int count = 0;
count++;
cout << "Function called " << count << " times." << endl;
}
In this example, the `countCalls` function has a `static` variable called `count`. Each time the function is called, the `count` variable is incremented and retains its value between function calls.
3. Global Variables:
- A global variable is a variable declared outside of any function, making it accessible to all functions in the program.
- Global variables have a global scope and can be accessed from anywhere in the program.
- Global variables are declared outside of any function and typically initialized at the top of the file.
Here's an example:
#include<iostream>
using namespace std;
int globalVar = 100;
void printGlobalVar()
{
cout << "Global variable: " << globalVar << endl;
}
int main()
{
printGlobalVar();
return 0;
}
In this example, `globalVar` is a global variable that is accessible to both the `printGlobalVar` function and the `main` function. The value of `globalVar` is 100, and it can be accessed and used throughout the program.