710 likes | 910 Views
C Part of C++. C++ is effectively a superset of ANSI C This module summarizes the C++ features that are also in ANSI C Experienced C programmers can skim through this module just to note differences between C and C++ in basic language constructs
E N D
C Part of C++ • C++ is effectively a superset of ANSI C • This module summarizes the C++ features that are also in ANSI C • Experienced C programmers can skim through this module just to note differences between C and C++ in basic language constructs • Programmers coming from other languages may find it helpful to review this module to get a fast start in C For use of Cleveland State's CIS459/559 Students only
Comments • C++ supports 2 styles of comments • Single-line comment // A single-line comment int k = 0; // Assign 0 to k; i.e. k is equal to 0 • Text to the right of symbols // is comment • Multiple-line comment /* Program Name: Comment.cpp Written On: January 2, 1998 Purpose: Demo of multiple-line comment */ For use of Cleveland State's CIS459/559 Students only
Identifiers • An identifier is a programmer defined word • Identifiers are used to name program constructs such as variables and functions • Identifiers may start with a letter or an underscore • May be followed by letters, digits and underscores • May be of any length • Some compiler may use the first 31 characters from the identifier name to distinguish one identifier from another For use of Cleveland State's CIS459/559 Students only
Identifiers • Example of valid identifiers interestRate i buffer_length p23 _list0 area_of_circle • Example of invalid identifiers if // key word, cannot be used as identifier 9go // cannot start with a digit -get_rate // uses a hyphen instead of underscore _Apple // _ followed by a capital is reserved for system use x__no // Double underscore is for system use For use of Cleveland State's CIS459/559 Students only
Identifiers • Identifiers are case sensitive • buffer and Buffer are two distinct identifiers • Identifier names should be meaningful • It is a good practice to avoid identifiers starting with one or more underscore, since they can be occasionally confused with system names For use of Cleveland State's CIS459/559 Students only
Keywords • C++ reserves a number of words that have strictly defined meaning within the language • These ‘reserved’ or keywords cannot be used in a program in any other manner • Keywords are used for declaring types of variables such as int, float, and char • They are used for specifying access levels for members of an object such as private, public and protected • All language defined words are keywords For use of Cleveland State's CIS459/559 Students only
Keywords For use of Cleveland State's CIS459/559 Students only
Variable Declaration • The general format for declaring a variable takes the form type var_name; where type is a C/C++ data type var_name is the variable that is of type ‘type’ • One or more variable names separated by coma can follow a data type in a variable declaration type var1, var2, var3; • A variable must be declared before it is first used, but the declaration may appear anywhere a statement may appear int smallNumber; // smallNumber is an integer int a, b, c, d; // a, b, c, and d are all integers For use of Cleveland State's CIS459/559 Students only
Initializing Variables • A variable can be declared and initialized in one statement type var_name = expression; int timeDelay = 200; int numberOfSteps = 2*45; int a, b = 20; // only b is 20 • Initial values are not restricted to be constants int taxRate = calculateTaxRate(); The above initialization will succeed only if the function calculateTaxRate is executable at the declaration point. For use of Cleveland State's CIS459/559 Students only
Primitive Data Types in C++ • C++ defines the following primitive types • bool, char, wchar_t, int, float, double • Some of the above can be modified by keyword modifiers: • short, long, signed, and unsigned • The range of values a variable can take depends upon implementation and is tied to underlying machine architecture For use of Cleveland State's CIS459/559 Students only
boolean Data Types and Variables • Specific to C++ and not available in C • Declaration bool b1 = false; • boolean variables can have 2 values: true, false • May be promoted to int with false becoming 0, and true becoming 1 • Implemented as 1 byte variable in MFC 6.0 For use of Cleveland State's CIS459/559 Students only
char Data Types • Used to store single characters or bytes • Declaration Definition char yesOrNo; char yesOrNo = ’N'; • May be modified with signed and unsigned prefix • Range of values char or signed char may take is -128 to 127; • unsigned char ranges between 0 and 255 • Examples signed char sc = 'b'; unsigned char usc = 'c'; For use of Cleveland State's CIS459/559 Students only
Character Constants • Character constants or literals are defined within a pair of single quotes ‘A’ ‘3’ ‘x’ • The escape character \ is used to define a number of nonprinting and special character literals ‘\a’ alert ‘\\’ Backslash ‘\b’ backspace ‘\r’ carriage return ‘\”’ double quote ‘\f’ form feed ‘\t’ tab ‘\n’ newline ‘\0’ null ‘\’’ single quote ‘\v’ vertical tab ‘\141’ octal 141, ascii ‘a’ ‘\x61’ Hex 61, ascii ‘a’ For use of Cleveland State's CIS459/559 Students only
Wide format char Data Type • An unsigned char can range between 0 and 255 • An unsigned char can encode 256 different characters • 256 is not a big enough number to encode languages of the world • A char that is 16 bit wide can represent a much larger set of languages • A 16 bit char can encode 216 = 65536 different characters • wchar_t type is a 16 bit character suitable for internationalization • Definition: wchar_t wt = 'd'; • A wide character literal can be specified as: wt = L’00’; For use of Cleveland State's CIS459/559 Students only
int Data Type • Integer data types are declared using int • Typically, ints are machine dependent • Integers can also be qualified as signed int, or unsigned int • Declaring ints int n; // n is a signed integer signed n; // n is a signed integer signed int n; // n is a signed integer unsigned int m; // m is an unsigned integer unsigned m; //m is an unsigned integer • short and long may be used to modify an int. • The number of bits used for a modified int is system-dependent For use of Cleveland State's CIS459/559 Students only
Defining modified int Data Types • Definitions of integers with modifiers short smallNumber = 2; int clientId = 200; long peopleCount = 203; unsigned short height = 20; unsigned index = 29; unsigned long weight = 2345; • Language specification requires the following relationships among various integer types sizeof(short) <= sizeof(int) <= sizeof(long) • Defaults: • Unless unsigned modifier is used, an integral type data is signed • The size of an int is machine dependent For use of Cleveland State's CIS459/559 Students only
Typical int sizes in MFC 6.0 • The table gives sizes for MFC 6.0 implementation Type size also called value range short 2 bytes signed short int –32,768 to 32,767 short int unsigned short 2 bytes unsigned short int 0 to 65,535 long 4 bytes signed long int –2,147,483,648 to long int 2,147,483,647 unsigned long 4 bytes unsigned long int 0 to 4,294,967,295 For use of Cleveland State's CIS459/559 Students only
float and double Data Types • float and double type of variables are used to specify Low and High-precision real (floating-point) numbers respectively • Defining real data types float f = 2.3F; double d = 4.56; long double ld = 45.56; • Size specification for MFC 6.0 implementation float 4 bytes Value range: 3.4E +/- 38 (7 digits) double 8 bytes Value range:1.7E +/- 308 (15 digits) long double 10 bytes Value range:1.2E +/- 4932 (19 digits) For use of Cleveland State's CIS459/559 Students only
Integer Constants • Decimal -12 // a decimal integer 12u // an unsigned integer; can also use U 12L // a long integer constant; can also use l 12ul // an Unsigned long integer • Octal 012 // an Octal integer constant • Hexadecimal 0x12FE // A hexadecimal integer constant • L, l used to designate Long • U, u used to designate Unsigned • long and Unsigned can be combined For use of Cleveland State's CIS459/559 Students only
Floating-Point Constants 3.14159 // a real constant, double 0.1234345 // a real constant, double 12.0f // a real constant; float 12.0L // a real constant, long double 314E-2 //a double, scientific notation • F or f can be used to designate single precision floating-point numbers • L or l can be used to designate long doubles • E or e can be used to specify the exponent in a scientific notation number For use of Cleveland State's CIS459/559 Students only
#include <iostream> using namespace std; int main() { bool b1 = false; char c1 = 'a'; signed char sc = 'b'; unsigned char usc = 'c'; wchar_t wt = 'd'; short s = 2; int i = 200; long l = 203; unsigned short us = 20; unsigned ui = 29; unsigned long ul = 2345; float f = 2.3; double d = 4.56; long double ld = 45.56; cout << "Print data types and their values" << endl; cout << "bool b1 = " << b1 << " and size = " << sizeof(b1) << endl; cout << "char c1 = " << c1 << " and size = " << sizeof(c1) << endl; cout << "signed char sc = " << sc << " and size = " << sizeof(sc) << endl; cout << "unsigned char usc = " << usc << " and size = " << sizeof(usc) << endl; cout << "wchar_t wt = " << (char)wt << " and size = " << sizeof(wt) << endl; cout << "short s = " << s << " and size = " << sizeof(s) << endl; cout << "int i = " << i << " and size = " << sizeof(i) << endl; cout << "long l = " << l << " and size = " << sizeof(l) << endl; cout << "unsigned short us = " << us << " and size = " << sizeof(us) << endl; cout << "unsigned ui = " << ui << " and size = " << sizeof(ui) << endl; cout << "unsigned long ul = " << ul << " and size = " << sizeof(ul) << endl; cout << "float f = " << f << " and size = " << sizeof(f) << endl; cout << "double d = " << d << " and size = " << sizeof(d) << endl; cout << "long double ld = " << ld << " and size = " << sizeof(ld) << endl; return 0; } Data Type Test in Microsoft Visual C++, 6.0 For use of Cleveland State's CIS459/559 Students only
Data Types in Microsoft Visual C++, 6.0 For use of Cleveland State's CIS459/559 Students only
const Modifier • const modifier is used to designate an object that is not modifiable in a program • constant objects must be initialized at the point of definition • Examples const double PI = 3.14159; const MAX_WINDOWS = 256; // defaults to int const char LETTER = ‘A’; • As a convention, constants are written using all upper case, multiple words separated by hyphen. • const modifier can be used instead of #define preprocessor directive For use of Cleveland State's CIS459/559 Students only
Assignment • The general format of an assignment is variable = expression; • Examples long peopleCount = 203; a = b + c; • The left side of assignment operator = must be a variable, i.e. has a storage location in memory • The right side of = is an expression. The expression is evaluated to a value that should match the type of the left side • Multiple assignments in one statement is allowed in C++ a = b + (c = 22); // same as c = 22; a = b+c; For use of Cleveland State's CIS459/559 Students only
C++ Operators • C/C++ can be considered as an expression-rich language with a rich set of operators For use of Cleveland State's CIS459/559 Students only
Arithmetic Expressions • The following binary and unary operators can be used with numeric typeswith expected results For use of Cleveland State's CIS459/559 Students only
Increment and Decrement Expressions • Integral variables can be incremented or decremented by 1 using the unary ++ and -- operators respectively • Order of increment or decrement changes based on prefix or postfix use of these operators For use of Cleveland State's CIS459/559 Students only
Bit operator: Left Shift • Bit operators are used for integral types • << Shift Left => Multiply the original value by 2d where d is the number of effective bits shifted int var1 = 100; var1 = var1 << 1; // var1 = 200 var1 = var1 << 2; // var1 = 400 var1 = var1 << 4; // var1 = 1600 int var2 = -50; var2 = var2 << 1; // var2 = -100; var2 = var2 << 2; // var2 = -200; var2 = var2 << 32; // var2 = -50;why? For use of Cleveland State's CIS459/559 Students only
Bit operator: Right Shift • >> Shift Right => Divide the original value by 2d where d is the number of effective bits shifted var1 ---> 01101011 var1 >> 1 ---> 00110101 var1 ---> 10101100 var1 >> 2 ---> 11101011 • Notice the fill bit is same as the sign bit int var1 = 100; var1 >>= 1; // var1 = 50 var1 >>= 2; // var1 = 25 int var2 = -400; var2 >>= 4; // var2 = -25 var2 = -2560; var2 >>= 8; // var2 = -10 • Calculation of effective bits if n is the number bits to be shifted for an integer, then d = n % 32 Therefore, var1 = var1 >> 32; assuming var1 is type int. • Effective bits calculated similarly for left shift operator For use of Cleveland State's CIS459/559 Students only
Bit operator: And, Or • & (And) Both bits need to be 1 for the result bit to be 1 11010011 int a = 0x40 & 0x62; 10110101 int b = b & 0377; _________ 10010001 • | (Or) Either bit must be 1 for the result bit to be 1 11010011 int a = 0800 | 0422; 10110101 int mask = mask | 0100; ________ 11110111 For use of Cleveland State's CIS459/559 Students only
Bit operator: XOR and Complement • ^ (Exclusive Or) Opposite bits result in 1, same bits in 0 11010011 10110101 ________ 01100110 int a = 0x40 ^ 0xB1; int code = code ^ 0x80; • ~ Complement (or One’s Complement): Reverse the bits var1 ---> 11001011 ~var1 ---> 00110100 For use of Cleveland State's CIS459/559 Students only
Shortcut Assignment Expression • C++ defines a number of shortcut assignment operators that combine the assignment operator (=) with another operator such as +, *, <<. For use of Cleveland State's CIS459/559 Students only
Statements • Semicolon is used to indicate the end of a statement • C++ supports a large variety of statements • Variable declarations: long peopleCount ; • In C++, variable declarations are considered statements and, therefore, can be placed anywhere in a program. In C, declarations must come first. • Assignment statements: peopleCount = 200; index++; cout << “Hello, World\n”; For use of Cleveland State's CIS459/559 Students only
Statements • Block statements: A series of statements grouped together, treated as a single statement { peopleCount = 200; index++; } • Control Flow statements: These include loops, conditions, and others that allow a programmer to control the order of execution. • Control flow statements are syntactically same as in C and may be skipped by a programmer versed in C. For use of Cleveland State's CIS459/559 Students only
Control Flow: if Construct • A program can make decisions using the if construct if (boolean expression) { // simple if action; } • action is executed if the boolean expression is evaluated to true. • action can be a block of statements char jobCode = ‘A’; if ( jobCode != ‘A’) { cout << “The employee is not a programmer” << endl; } For use of Cleveland State's CIS459/559 Students only
Control Flow: if Construct • An if statement can have an optional else component if (boolean expression) { truth action; } else { false action; } • truth action is executed if the boolean expression is true • false action is executed if the boolean expression is false • Both truth and false action can be a block that includes other control flow constructs including other ifs and loops. For use of Cleveland State's CIS459/559 Students only
Control Flow: if Construct char jobCode = ‘A’; if ( jobCode != ‘A’) { cout << “The employee is not a programmer” << endl; cout << “Pay the employee from staff budget” << endl; } else { cout << “The employee is a programmer” << endl; cout << “Salary is from project budget” << endl; } • A boolean expression uses relational and/or logical operators For use of Cleveland State's CIS459/559 Students only
Relational operators • Six relational operators are defined • Numbers are compared algebraically • Characters are compared using the underlying collating sequence For use of Cleveland State's CIS459/559 Students only
Logical operators • Three logical operators are defined • Boolean And &&: All booleans connected by && must be true for the entire expression to be true • Boolean Or || : Only one of the booleans connected by || need to be true for the entire expression to be true • And precedes Or • Boolean expressions are evaluated left to right For use of Cleveland State's CIS459/559 Students only
Short-circuit evaluation of expressions connected by logical operators • Evaluation of a boolean expression continues only until the final outcome can be determined; the entire expression may not be evaluated • (( 5 < 2) && (3 < 4)) The second half of the above (3 < 4) is not evaluated since (5 < 2) is false i.e. the final outcome of the boolean is known as soon as (5 < 2) is evaluated to false • ((1 < 2) || ( 4 != 5)) The second half of this boolean (4 != 5) is not evaluated since (1 < 2) is true i.e. the final outcome is known as soon as (1 < 2) is evaluated to true For use of Cleveland State's CIS459/559 Students only
boolean expressions • A boolean expression in C++ evaluates to a type bool, not int as in C • However, bool can be promoted to int int a = ( 5 > 2); // assigns 1 to a • Conditional evaluation operator (?:) can also be used with boolean expressions booleanExpression ? expr1 : expr2; • expr1 is evaluated if the booleanExpression is true, otherwise expr2 is evaluated int a = ( b > c) ? b : c; // b is assigned to a if b > c // c is assigned to a if !(b>c) For use of Cleveland State's CIS459/559 Students only
Nesting ifs • Assuming b1, b2, b3 to be boolean expressions if ( b1) if (b2) if (b3) action1; // executed if all of b1, b2, b3 are true else action2; // executed if b1, b2 are true, b3 is false else action3; // executed if b1 is true, b2 is false else action4; // executed if b1 is false • Each action can be a block For use of Cleveland State's CIS459/559 Students only
Nesting ifs • Assuming b1, b2, b3 to be boolean expressions if ( b1) action1; // executed if b1 is true else if (b2) action2; // executed if b1 is false and b2 is true else if (b3) action3; // executed if b1, b2 are false and b3 is true else action4; // executed if all of b1, b2, and b3 are false • Each action can be a block For use of Cleveland State's CIS459/559 Students only
Examples of if statements • find whether a number is even and greater than 100 int number; cout << “Enter a number” “; cin >> number; if ((number > 100) && (number % 2) == 0) cout << number << “ is even and > 100” << endl; else cout << number << “ is either odd or <= 100” << endl; For use of Cleveland State's CIS459/559 Students only
Examples of if statements • print the sign of a given number int number; cout << “Enter a number” “; cin >> number; if (number > 0) cout << number << “ is positive” << endl; else if (number == 0) cout << number << “ is zero” << endl; else cout << number << “ is negative” << endl; For use of Cleveland State's CIS459/559 Students only
switch Statement • Syntax switch (selection expression) { case constant1: //action for constant1 break; case constant2: //action for constant2 break; case constant3: //action for constant3 break; default: //default action break; } For use of Cleveland State's CIS459/559 Students only
switch Statement • selection expression is an integral expression • Each case defines a constant • break is an optional entry and in its absence, execution continues until a break is encountered or the switch statement is completed • default is an optional entry and is executed if none of the specified cases match For use of Cleveland State's CIS459/559 Students only
Example of a switch Statement • Select an option from a set of choices char option; cout << “Please enter an option: “; cin >> option; switch (option) { case ‘a’: cout << “You typed an ‘a’\n”; break; case ‘d’: cout << “You typed a ‘d’\n”; break; case ‘x’: case ‘q’: cout << “You typed a ‘x’ or ‘q’\n”; break; default: cout << “You did not type any of the choices\n”; break; } For use of Cleveland State's CIS459/559 Students only
Control Flow: while statement • while statement allows a set of tasks to be executed iteratively • The while statement has the form while (boolean expression) action; • The order of operation of while statement • Evaluate the boolean expression • If the boolean expression is true, execute the action, and then re-evaluate the boolean expression • If the boolean expression is false, exit the loop • The action can be a block and include any valid C++ statement including other loops For use of Cleveland State's CIS459/559 Students only
while Statement example • count up to a given number int index, lastNumber; cout << “Enter last number: “; cin >> lastNumber; index = 0; while (index <= lastNumber) { cout << index << “\n”; index++; } For use of Cleveland State's CIS459/559 Students only