Chapter 4 Literals, Variables and Constants

43
#Page 1 Chapter 4 Literals, Variables and Constants Spring 2014

description

Chapter 4 Literals, Variables and Constants. Spring 2014. Chapter 4 Literals, Variables and Constants. 4.1 Literals. A literal is a value that is interpreted as it is written Any numeric literal starting with 0x specifies that the following is a hexadecimal value - PowerPoint PPT Presentation

Transcript of Chapter 4 Literals, Variables and Constants

Page 1: Chapter 4  Literals, Variables and Constants

#Page 1

Chapter 4 Literals, Variables and Constants

Spring 2014

Page 2: Chapter 4  Literals, Variables and Constants

Chapter 4

Literals, Variables and

Constants

Page 3: Chapter 4  Literals, Variables and Constants

#Page 3

4.1 Literals

A literal is a value that is interpreted as it is written

Any numeric literal starting with 0x specifies that the following is a hexadecimal value

0xFF – this is a hexadecimal value

Any numeric literal starting with 0 is an octal value

0777 – this is an octal value

Page 4: Chapter 4  Literals, Variables and Constants

#Page 4

4.1 Literals

Character literals - single characters placed between apostrophes (‘)

‘a’

String literals - one or more characters placed between quotes ( “ )

“string”

Usually, treat single character as a character literal

Page 5: Chapter 4  Literals, Variables and Constants

#Page 5

4.2 Escape Sequences

Escape sequence - exception to the rule that literals are interpreted exactly as they are written

Escape sequences start with a backslash (\) followed by a single character

Two types of escape sequences• Character• Numeric

Page 6: Chapter 4  Literals, Variables and Constants

#Page 6

4.2.1 Character Escape Sequences

Can be embedded in a string literal or be used as a character literal

Null character - a special character used, among other things, to give a character variable an initial value

C++ is case sensitive, so \T is not a tab

EscapeSequence

Character Representation

\nCarriage return and line feed (new line)

\tTab (eight characters wide)

\" Double quote

\' Single quote

\\ Backslash

\0 Null character

Page 7: Chapter 4  Literals, Variables and Constants

#Page 7

4.2.1 Character Escape Sequences

cout << "This is on one line\n This is on another\n";cout << "\tHe said, \"Stop!\"";

// OutputThis is on one line This is on another He said, "Stop!"

cout << "This is an apostrophe: ";

cout << '\'';

// OutputThis is an apostrophe: '

Page 8: Chapter 4  Literals, Variables and Constants

#Page 8

4.3 Variable Declarations

Variable - a placeholder whose contents can change

Everything must be declared before it is used

Page 9: Chapter 4  Literals, Variables and Constants

#Page 9

4.3 Variable Declarations

A variable declaration has several purposes:• informs operating system how much internal memory

(RAM) the variable will need

• identifies the memory address to use for that variable

• identifies the type of data to be stored in that physical memory location

• indicates what operations (i.e., +, -, /, etc.) can be performed on the data contained within that variable

Page 10: Chapter 4  Literals, Variables and Constants

#Page 10

4.3 Variable Declarations

Basic declaration syntax<data type> identifier;

Data types discussed in the next section

Identifier - the variable name

int salary; // Notice the semicolon

Page 11: Chapter 4  Literals, Variables and Constants

#Page 11

4.3 Variable Declarations

Multiple variables can be declared in the same statement

int age, iq, shoe_size;

Variables can be declared anywhere as long as they are declared before used

Usually good idea to have all declarations at beginning of program

Page 12: Chapter 4  Literals, Variables and Constants

#Page 12

4.3.1 Variable’s Initial Value

When declared, its initial value is unknown

Important to provide an initial value for all variables

Initialization - process of giving a variable a value during its declaration - resulting in the variable always being in a known state

int sum = 0; //literalint Ralphs_age = RETIREMENT_AGE; //constant valueint Randys_age = Ralphs_age - 26; //variable

Page 13: Chapter 4  Literals, Variables and Constants

#Page 13

4.3.1 Variable’s Initial Value

Can initialize a variable to another variable’s value

<data type> identifier2 = identifier;

Initialization is the process of giving a variable a value during its declaration. As a result, the variable will always be in a known state.

int base_salary = 30000;

int num_dependents, staff_salary = base_salary;

Page 14: Chapter 4  Literals, Variables and Constants

#Page 14

4.3.1 Variable’s Initial Value

Another form of initialization - uses parentheses instead of the assignment operator

int base_salary( 30000 );

int num_dependents, staff_salary( base_salary );

Page 15: Chapter 4  Literals, Variables and Constants

#Page 15

4.3.2 Initialization

Always know the state, or value, of all variables

Variables should always be initialized

If you do not initialize, value unknown

Variables, even characters, are usually initialized to 0

Page 16: Chapter 4  Literals, Variables and Constants

#Page 16

4.3.3 Data Types

A data type:• Specifies how much memory a variable will

take up in memory

• Indicates operations that can be performed on the variable

Primitive data type - data type whose definition is built into the language

Page 17: Chapter 4  Literals, Variables and Constants

#Page 17

4.3.3 Primitive Data TypesC++

Data TypeDescription of Data

Memory Allocated

Range

char Character 1 byte -128 to 127

int Integer OS Dependent OS Dependent

float Floating point (decimal) 4 bytes3.4E +/- 38 with 7 digits of accuracy

doubleDouble precision floatingpoint

8 bytes1.7E +/- 308 with 15 digits of accuracy

bool Boolean data 1 byte true or false

short (or short int)

Smaller integer 2 bytes –32,768 to 32,767

long Larger integer 4 bytes–2,147,483,648 to2,147,483,647

long double Larger double 8 bytes1.7E +/- 308 with 15 digits of accuracy

Page 18: Chapter 4  Literals, Variables and Constants

#Page 18

4.3.3 Data Types

Boolean value - either true or false

Size of an integer (int) - dependent upon the operating system• On a 16-bit operation system such as Windows

3.x, an integer is 16 bits, or 2 bytes

• On a 32-bit operation system (Windows XP), an integer is 32 bits, or 4 bytes

Page 19: Chapter 4  Literals, Variables and Constants

#Page 19

4.3.3 Data Types

Size of an integer (int) - dependent upon the operating system (continued)

• On a 64-bit operation system - some versions of Windows Vista - an integer is 64 bits, or 8 bytes

Page 20: Chapter 4  Literals, Variables and Constants

#Page 20

4.3.3 Data Types

The amount of memory an integer requires determines the range of values

In a 32-bit operating system - since a bit can have one of two values - there will be 232 different possibilities

Page 21: Chapter 4  Literals, Variables and Constants

#Page 21

4.3.3 Data Types

Most significant bit is used as a sign bit• Zero meaning the number is positive

• One means its negative

• Therefore, left with 31 bits, or 231 different values

Page 22: Chapter 4  Literals, Variables and Constants

#Page 22

4.3.3 Data TypesUnsigned prefix for integral data types - the

sign bit is used for data instead of the sign

Integral data type - only holds whole numbers• A char data type is an integral data type • Under the hood a char holds an ASCII number

representing a character

Use smallest data type that will work with the data

Page 23: Chapter 4  Literals, Variables and Constants

#Page 23

4.3.4 The sizeof Operator

sizeof operator - determines number of bytes required for a specific data type

// Part 1cout << sizeof( char ) << '\n';

// Part 2unsigned short age = 21; cout << sizeof( age ) << '\n';

// Output12

Page 24: Chapter 4  Literals, Variables and Constants

#Page 24

4.3.5 Numeric Literal Suffixes

Numeric literal suffix - special character used to specify the type of literal

Numeric literal with an F suffix specifies a float, while L specifies a long value

Page 25: Chapter 4  Literals, Variables and Constants

#Page 25

4.3.5 Numeric Literal Suffixes

Either case will work for suffixes – but use capitals to avoid confusion between lower case l and a numeric 1

float money = 123.45F;// Flt pt (4 bytes) numericfloat avg = 95.5f; // literals are treated as long flag = 0L; // doubles (8 bytes) // Last character is not a one but a lowercase llong salary = 50000l;

Page 26: Chapter 4  Literals, Variables and Constants

#Page 26

4.3.6 Naming Rules

Variable naming rules:• Only made up of letters, digits and underscores

• abcdefghijklmnopqrstuvwxyz• ABCDEFGHIJKLMNOPQRSTUVWXYZ• 0123456789• _

• Can’t start with a digit (must begin with a letter or underscore)

• name01 is OK, 01name is not

• Can’t be a reserved word (if, else, while, etc.)• Else is OK as well as else1

Variable names should be descriptive, aiding in code readability

Page 27: Chapter 4  Literals, Variables and Constants

#Page 27

Identifiers

• An identifier is a sequence of characters used to denote one of the following:• Object or variable name• Class, structure, or union name• Enumerated type name• Member of a class, structure, union, or enumeration• Function or class-member function• typedef name• Label name• Macro name• Macro parameter

Page 28: Chapter 4  Literals, Variables and Constants

#Page 28

Identifiers (cont.)• The following characters are legal as the first character of

an identifier, or any subsequent character:• _ a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M

N O P Q R S T U V W X Y Z

• The following characters are legal as any character in an identifier except the first:• 0 1 2 3 4 5 6 7 8 9

• Cannot be the exact spelling and case as keywords• Identifiers that contain keywords are legal

• Pint

• Use of two underscore characters (__) at the beginning of an identifier, or a single leading underscore followed by capital letter, is reserved for C++ implementation

Page 29: Chapter 4  Literals, Variables and Constants

#Page 29

4.4 ASCII Characters

ASCII chart - associates characters with a number (page 630 in textbook)

American Standard Code for Information Interchange (ASCII)

Page 30: Chapter 4  Literals, Variables and Constants

#Page 30

ASCII Table and Description

Page 31: Chapter 4  Literals, Variables and Constants

#Page 31

4.4 ASCII Characters

Allow for the storage of characters in memory

Some important ASCII values:• 65 = ‘A’ (4116, 010000012)

• 97 = ‘a’ (6116, 011000012)

• 32 = ‘ ’ (space, 2016, 001000002)

• 48 = ‘0’ (character zero, 3016, 001100002)

The number 010 is stored as 0016, 000000002

The number 2010 is stored as 1416, 000101002

Page 32: Chapter 4  Literals, Variables and Constants

#Page 32

4.4 ASCII Characters

To display characters given an ASCII value use numeric escape sequences

cout << "Hexadecimal ASCII character: " << "\x4E" << endl;cout << "Octal ASCII character: " << "\77" << endl;

cout << "Hexadecimal number: " << 0x4E << endl;cout << "Octal number: " << 077 << endl;

//OutputHexadecimal ASCII character: NOctal ASCII character: ?Hexadecimal number: 78Octal number: 63

Page 33: Chapter 4  Literals, Variables and Constants

#Page 33

4.5 Constants

Constants - identifiers that have a value that will never change• Aid in code readability and maintainability

• Should have a name that is descriptive of their purpose

const int SPEED_LIMIT = 65;const int RETIREMENT_AGE = 67;const double PI = 3.1416;

Page 34: Chapter 4  Literals, Variables and Constants

#Page 34

4.6 const versus #define

To declare constants use the #define preprocessor directive

#define SPEED_LIMIT 65 // Notice no = or semicolons#define RETIREMENT_AGE 67#define PI 3.14

Preprocessor searches through the code replacing the identifier with the value associated with it

Page 35: Chapter 4  Literals, Variables and Constants

#Page 35

4.6 const versus #define

#define statements can cause compilation errors while looking syntactically correct

#define PI = 3.14; // Notice the = and ;

int main(){ int circumference = 0, radius = 5; circumference = 2 * PI * radius; return 0;}

Page 36: Chapter 4  Literals, Variables and Constants

#Page 36

4.6 const versus #define

Although the statement looks correct, it causes a compilation error

circumference = 2 * PI * radius;

Error becomes clearer if we show what was created by the preprocessor

circumference = 2 * = 3.14; * radius;

Page 37: Chapter 4  Literals, Variables and Constants

#Page 37

4.6 const versus #define

Use const versus #define because:

• const uses a data type and participates in type checking

• const has scope

Page 38: Chapter 4  Literals, Variables and Constants

#Page 38

4.7 Bringing It All Together

Useful to picture how variables and constants might be placed in memory

Examine the declarations below:

short int age;char grade = 'A';float gpa(0.0);const float PI = 3.14;

Page 39: Chapter 4  Literals, Variables and Constants

#Page 39

4.7 Bringing It All Together

They may be placed in memory as shown below:

? ? A 0 0 0 0 3 . 1 4

agegrade

gpa PI

Page 40: Chapter 4  Literals, Variables and Constants

#Page 40

Remember, pseudocode is a language independent representation of an algorithm

Using data types has a tendency to make the solution to closely tied to C++ (or any other language)

4.8 Variable Declarations in Pseudocode

Page 41: Chapter 4  Literals, Variables and Constants

#Page 41

4.8 Variable Declarations in Pseudocode

Do not put variable declarations in pseudocode

#includes are not specified in pseudocode and are considered necessary overhead to the algorithm

Page 42: Chapter 4  Literals, Variables and Constants

4.10 C – The Differences• C doesn’t have a Boolean data type (and no true or false)

• Doesn’t allow for the use of parentheses to initialize variables or constants

• In older versions of C, variables must be declared as the first statement in a block of code (after an opening curly brace)

Page 43: Chapter 4  Literals, Variables and Constants

4.10 C – The Differences

Current C standard allows a programmer to use const to create constants

Legacy C programs written must use the #define to create constants