Chapter 4 - Literals, Variables and Constants

Download Report

Transcript Chapter 4 - Literals, Variables and Constants

Chapter 4
Literals,
Variables and
Constants
4.1 Literals
Any numeric literal starting with 0x specifies
that the following is a hexadecimal value
Any numeric literal starting with 0 is an octal
value
#Page
2
4.1 Literals
Character literals - single characters placed
between apostrophes (‘)
String literals - one or more characters
placed between quotes ( “ )
Usually, treat single character as a character
literal
#Page
3
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
4
4.2.1 Character Escape Sequences
Can be embedded in a
string literal or be used
as a character literal
Escape
Sequence
Character
Representation
\n
Carriage return
and line feed (new
line)
Null character - a
special character used,
among other things, to
give a character
variable an initial value
\t
Tab (eight
characters wide)
\"
Double quote
\'
Single quote
\\
Backslash
\0
Null character
#Page
5
4.2.1 Character Escape Sequences
cout << "This is on one line\n This is on another\n";
cout << "\tHe said, \"Stop!\"";
// Output
This is on one line
This is on another
He said, "Stop!"
cout << "This is an apostrophe: ";
cout << '\'';
// Output
This is an apostrophe: '
#Page
6
4.3 Variable Declarations
Variable - a placeholder whose contents can
change
Everything must be declared before it is used
#Page
7
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
8
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
9
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
#Page
10
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;
int Ralphs_age = RETIREMENT_AGE;
int Randys_age = Ralphs_age - 26;
#Page
11
4.3.1 Variable’s Initial Value
Can initialize a variable to another variable’s
value
<data type> identifier2 = identifier;
int base_salary = 30000;
int num_dependents, staff_salary = base_salary;
#Page
12
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
13
4.3.2 Initialization
Always know the state, or value, of all
variables
Variables should always be initialized
Variables, even characters, are usually
initialized to 0
#Page
14
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
15
4.3.3 Data Types
C++
Data Type
Description of Data
Memory
Allocated
Range
char
Character
1 byte
-128 to 127
int
Integer
OS Dependent
OS Dependent
float
Floating point (decimal)
4 bytes
3.4E +/- 38 with
7 digits of accuracy
double
Double precision floating
8 bytes
point
1.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 to
2,147,483,647
long double
Larger double
8 bytes
1.7E +/- 308 with
15 digits of accuracy
#Page
16
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
17
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
18
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
19
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
20
4.3.3 Data Types
Unsigned 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
21
4.3.4 The sizeof Operator
sizeof operator - determines number of
bytes required for a specific data type
// Part 1
cout << sizeof( char ) << '\n';
// Part 2
unsigned short age = 21;
cout << sizeof( age ) << '\n';
// Output
1
2
#Page
22
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
23
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;//
float avg = 95.5f;
//
long flag = 0L;
//
// Last character is not
long salary = 50000l;
Flt pt (4 bytes) numeric
literals are treated as
doubles (8 bytes)
a one but a lowercase l
#Page
24
4.3.6 Naming Rules
Variable naming rules:
• Only made up of letters, digits and underscores
• Can’t start with a digit (must begin with a letter
or underscore)
• Can’t be a reserved word (if, else, while,
etc.)
Variable names should be descriptive, aiding
in code readability
#Page
25
4.4 ASCII Characters
ASCII chart - associates characters with a
number
American Standard Code for Information
Interchange (ASCII)
#Page
26
4.4 ASCII Characters
Allow for the storage of characters in memory
Some important ASCII values:
•
•
•
•
65 = ‘A’
97 = ‘a’
32 = ‘ ’
48 = ‘0’
#Page
27
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;
//Output
Hexadecimal ASCII character: N
Octal ASCII character: ?
Hexadecimal number: 78
Octal number: 63
#Page
28
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
29
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
30
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
31
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
32
4.6 const versus #define
Use const versus #define because:
• const uses a data type and participates in type
checking
• const has scope
#Page
33
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
34
4.7 Bringing It All Together
They may be placed in memory as shown
below:
? ? A 0 0 0 0 3 . 1 4
age
grade
gpa
PI
#Page
35
4.8 Variable Declarations in Pseudocode
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)
#Page
36
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
37
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)
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