A variable is a name that is assigned to a memory location. It is the fundamental storage unit in a program. In C++, each variable has a type that determines the size and layout of the variable’s memory, the range of values that can be stored within that memory, and the set of operations that can be applied to the variable.
Type | Description |
---|---|
bool | Stores either value true or false. |
char | Typically a single octet (one byte). This is an integer type. |
int | The most natural size of integer for the machine. |
float | A single-precision floating point value. |
double | A double-precision floating point value. |
void | Represents the absence of type. |
wchar_t | A wide character type. |
A variable declaration assures the compiler that there is only one variable of the given type and name, allowing the compiler to proceed with further compilation without needing complete information about the variable.
A variable definition tells the compiler where to store the variable and how much storage to allocate.
Initialization means assigning value to an already declared variable,
int i; // declaration
i = 10; // initialization
A scope is a program region, and there are three places where variables can be declared in general.
Local variables are variables declared within a function or block. They can only be used by statements within that function or block of code. Local variables are unknown to functions other than their own.
#include <iostream>
using namespace std;
int main () {
// Local variable declaration:
int a=11, b=1;
if(a>b){
//local variable
int c = a - b;
}
cout << c;
return 0;
}
/tmp/XDf9Q9w7we.cpp: In function 'int main()':
/tmp/XDf9Q9w7we.cpp:13:12: error: 'c' was not declared in this scope
13 | cout << c;
| ^
Global variables are defined outside all functions, usually at the program’s top. The global variables will retain their value for the duration of the program.
#include <iostream>
using namespace std;
// Global variable declaration:
int a=11, b=1,c;
int main () {
if(a>b){
c = a - b;
}
cout << c;
return 0;
}
10
Note: also read about the OOPs Concepts in C++
If you like my post, please follow me to read my latest post on programming and technology.
https://www.instagram.com/coderz.py/
https://www.facebook.com/coderz.py
Staying up to the mark is what defines me. Hi all! I’m Rabecca Fatima a keen learner, great enthusiast, ready to take new challenges as stepping stones towards flying colors.
Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…
Given an integer A. Compute and return the square root of A. If A is…
Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…
A heap is a specialized tree-based data structure that satisfies the heap property. It is…
What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…