05 Constants and Variables
05 Constants and Variables
1
Constants
• Constants are specific values of any data type,
such as
2 3.145 -2.3 ‘f’ “hello”
• Character constants are enclosed in single quotes
char ch = ‘z’;
3
#include <iostream.h>
int main()
{
char ch = ‘M’; //assign ASCII code for M to c
int number = ch; //store same code in an int
return 0;
}
4
Variables
• Needed to store information
• Program must remember three properties: where,
what value, what kind
int age;
age = 40;
double radius = 0.0;
• Have to be declared first; why?
• Uninitialized variables have garbage values
• C++ is case-sensitive
5
Scope of Variables
• Local
• Global
• Block
• Function
• File
• Program
• Class ?
6
Local Variables
• Declared inside a function
• Die when function finishes; unknown outside
their function
• Initialized each time the function containing
them is entered; uninitialized have garbage
values
7
#include <iostream.h>
void func()
{
int x; // local to func()
x = -199;
cout << x; // displays ?
}
int main()
{
int x; // local to main()
x = 10;
func();
return 0;
8
}
Global Variables
• Declared outside any function; have life as long as the
program runs
• Can be used by all following functions
• Usually placed at the beginning of program
• Initialized only at the start of the program;
uninitialized default to zero
• An identically named local variable masks global one
• Should be avoided if possible
9
#include <iostream.h>
int i = 2; //global
void func()
{
cout << i << endl;
int i = 3; //local
cout << i << endl;
}
int main()
{
cout << i << endl;
func();
int i = 5;
cout << i << endl;
return 0; 10
}