Docsity

Constants and Variables in C++: Lecture 5 of CS 192, Fall 2011, Slides of Computer Programming

Partial preview of the text

Download Constants and Variables in C++: Lecture 5 of CS 192, Fall 2011 and more Slides Computer Programming in PDF only on Docsity!

1

CS 192Lecture 5Fall 2011

September 23, 2011

Ghufran Ahmed

2

Constants

• Constants are specific values of any data type,

such as

‘f’

“hello”

• Character constants are enclosed in single quotes

char ch = ‘z’;

•^

String constants are enclosed in double quotes

string message = “Hello”;

4

#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

in

ch; cout

“The

ASCII

code

for

ch

is

in

endl;

return

5

Variables

•^

Needed to store information

•^

Program must remember three properties: where,what value, what kind^ int

age; age

double

radius

•^

Have to be declared first; why?

•^

Uninitialized variables have

garbage values

•^

C++ is case-sensitive

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 garbagevalues

8

#include

<iostream.h>

void

func() { int

x;

local

to

func()

x^

=^

cout

x;

displays

} int

main() { int

x;

local

to

main()

x^

=^

func();cout

"\n";

cout

x;

displays

return

10

#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; }