Professional Documents
Culture Documents
VARIABLES and CONSTANTS IN C++
VARIABLES and CONSTANTS IN C++
2
V arIables
and
C onstants
1 Computer programming in C++ Chapter 2: Variables and Constant
The constants, variables and keyword
are mainly made up of alphabets,
numbers and special symbols.
Alphabets : A,B………YZa,b……….y,z
Digits : 0,1,2,3,4,5,6,7,8,9
Special symbols:
~,’,!@#$%^&*()}{][“:’;?></.,
a = 5;
b = 2;
a = a + 1;
result = a - b;
VARIABLE TYPES
• int a;
• float mynumber;
Example:
int a, b, c; This declares three variables
(a, b and c), all of them of type int, and
has exactly the same meaning as:
int a;
int b;
int c;
Local variables
The scope of local variables is limited to
the block enclosed in braces ({}) where
they are declared. For example, if they are
declared at the beginning of the body of a
function (like in function main) their
scope is between its declaration point and
the end of that function.
Computer programming in C++ Chapter 2:
14 Variables and Constant
Example:
#include <iostream>
using namespace std;
int a=5; // a is global variable
int main()
{
int b=15,c; // b and c are local variable
c=a+b;
cout <<"sum ="<<c;
return 0;
}
Example:
int a (0);
#include <iostream>
using namespace std;
int main ()
{
int a=5;
// initial value = 5
int b(2);
// initial value = 2
int result;
// initial value undetermined
a = a + 3;
result = a - b;
cout<< result; return 0;
} Computer programming in C++ Chapter 2:
18 Variables and Constant
DEFINED CONSTANTS (#DEFINE)
Example:
#define PI 3.14159265
#define NEWLINE '\n‘
Computer programming in C++ Chapter 2:
19 Variables and Constant
DEFINED CONSTANTS (const)
We can also define constant by using
const keyword.
Example:
2
V a r i a b l e s
and
C onstants
Computer programming in C++ Chapter 2:
22 Variables and Constant