Variables in C++

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 8

Variables in C++

Variables

A variable is a name which is associated with a value that


can be changed. For example when I write int
num=20; here variable name is num which is associated
with value 20, int is a data type that represents that this
variable can hold integer values. We will cover the data
types in the next tutorial. In this tutorial, we will discuss
about variables.
Syntax in declaring variables

data_type variable1_name = value1, variable2_name = value2;

Example:

int num1=20, num2=100;


Types of variables
• int: These type of of variables holds integer value.
• char: holds character value like ‘c’, ‘F’, ‘B’, ‘p’, ‘q’ etc.
• bool: holds boolean value true or false.
• double: double-precision floating point value.
• float: Single-precision floating point value.
Types of variables based on scope
1. Global variable
2. Local variable
Global variables
A variable declared outside of any function (including main as well) is
called global variable. Global variables have their scope throughout the
program, they can be accessed anywhere in the program, in the main,
in the user defined function, anywhere.
Example:
#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
int main() {
cout <<"Value of myVar: "<< myVar<<endl; myVar='Z';
cout <<"Value of myVar: "<< myVar; return 0; }
Output:
Value of myVar: A Value of myVar: Z
Local variables
Local variables are declared inside the braces of any user defined function,
main function, loops or any control statements(if, if-else etc) and have their
scope limited inside those braces.
Example:
#include <iostream>
using namespace std;
char myFuncn() {
// This is a local variable
char myVar = 'A';
}
int main() {
cout <<"Value of myVar: "<< myVar<<endl; myVar='Z';
cout <<"Value of myVar: "<< myVar;
return 0;
}
Can global and local variable have same name
in C++?
#include <iostream>
using namespace std;
// This is a global variable
char myVar = 'A';
char myFuncn() {
// This is a local variable
char myVar = 'B';
return myVar;
}
int main() {
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
myVar='Z';
cout <<"Funcn call: "<< myFuncn()<<endl;
cout <<"Value of myVar: "<< myVar<<endl;
return 0; }
Output:
Funcn call: B
Value of myVar: A
Funcn call: B
Value of myVar: Z

You might also like