Lecture 4
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’;
• String constants are enclosed in double quotes
string message = “Hello”;
2
Types of Constants
Character constants char c = ‘z’
Numeric constants int a = 10;
Hexadecimal constants int hex = 0xFF;
Octal constants int oct = 011;
String constants char greetings = “Hello”;
Backslash constants \b, \f, \n, \r, \t, \”, \’, \0, \\,
\v, \a, \?, \OCTAL, \xHEX
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
cout << “The ASCII code for “ << ch << “ is ”
<< in << ‘\n’;
cout << “Add one to the character code\n”;
ch = ch + 1;
in = ch;
cout << “The ASCII code for “ << ch << “ is “
<< in << endl;
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();
cout << "\n";
cout << x; // displays ?
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();
cout << i << endl;
int i = 5;
cout << i << endl;
return 0; 10
}