430 likes | 615 Views
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
E N D
Chapter 4 Literals, Variables and Constants Spring 2014
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
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
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
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
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: '
4.3 Variable Declarations • Variable - a placeholder whose contents can change • Everything must be declared before it is used
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
4.3 Variable Declarations • Basic declaration syntax <data type> identifier; • Data types discussed in the next section • Identifier -the variable name • intsalary; // Notice the semicolon
4.3 Variable Declarations • Multiple variables can be declared in the same statement • intage, 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
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 • intsum = 0; //literal • intRalphs_age = RETIREMENT_AGE; //constant value • intRandys_age = Ralphs_age - 26; //variable
4.3.1 Variable’s Initial Value • intbase_salary = 30000; • intnum_dependents, staff_salary = base_salary; 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.
4.3.1 Variable’s Initial Value • Another form of initialization - uses parentheses instead of the assignment operator • intbase_salary( 30000 ); • intnum_dependents, staff_salary( base_salary );
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
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
4.3.3 Data Types • Booleanvalue - 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
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
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
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
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
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 • unsignedshort age = 21; • cout<<sizeof(age ) <<'\n'; • // Output • 1 • 2
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
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 • floatmoney = 123.45F;// Flt pt (4 bytes) numericfloat avg = 95.5f;// literals are treated aslong flag = 0L;// doubles (8 bytes) • // Last character is not a one but a lowercase l • long salary = 50000l;
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
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
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
4.4 ASCII Characters • ASCII chart - associates characters with a number (page 630 in textbook) • American Standard Code for Information Interchange (ASCII)
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
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
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 • constintSPEED_LIMIT = 65; • constintRETIREMENT_AGE = 67; • constdoublePI = 3.1416;
4.6 const versus #define • To declare constants use the #define preprocessor directive • #defineSPEED_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
4.6 const versus #define • #define statements can cause compilation errors while looking syntactically correct • #definePI = 3.14;// Notice the = and ; • intmain() • { • intcircumference = 0, radius = 5; • circumference = 2 * PI * radius; • return0; • }
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;
4.6 const versus #define • Use const versus #define because: • const uses a data type and participates in type checking • const has scope
4.7 Bringing It All Together • Useful to picture how variables and constants might be placed in memory • Examine the declarations below: • short intage; • char grade ='A'; • float gpa(0.0); • const floatPI = 3.14;
? • ? • A • 0 • 0 • 0 • 0 • 3 • . • 1 • 4 • age • gpa • PI • grade 4.7 Bringing It All Together • They may be placed in memory as shown below:
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)
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
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 constto create constants Legacy C programs written must use the #define to create constants