1 cs 192 lecture 5 winter 2003 december 10-11, 2003 dr. shafay shamail
Post on 30-Dec-2015
215 Views
Preview:
TRANSCRIPT
1
CS 192
Lecture 5
Winter 2003
December 10-11, 2003
Dr. Shafay Shamail
2
Constants
• Constants are specific values of any data type, such as
2 3.145 -2.3 ‘f’ “hello”
• Character constants are enclosed in single quoteschar ch = ‘z’;
• String constants are enclosed in double quotes
string message = “Hello”;
3
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
4
#include <iostream.h>
int main(){
char ch = ‘M’; //assign ASCII code for M to cint 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;}
5
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
6
Scope of Variables
• Local• Global
• Block• Function• File• Program
• Class ?
7
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
8
#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;}
9
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
10
#include <iostream.h>
int i = 2; //global
void func(){
cout << i << endl;int i = 3; //localcout << i << endl;
}
int main(){
cout << i << endl;
func();
cout << i << endl;
int i = 5;cout << i << endl;
return 0;}
top related