C++ Programming Basics Chapter 2 and pp. 634-640 Copyright 1998-2011 Delroy A. Brinkerhoff. All Rights Reserved. CS 1410 Chapter 2 Slide 1 of 25
Program Components Function main P Every C/C++ program has exactly one function named main < main is not a keyword but should be treated as if it was < main is where the (apparent) program execution begins (it is called by the system) PFunctions have 4 parts < Name < Return value type < Argument list < Body { } int main ( ) body (a block ) return value type name argument list header CS 1410 Chapter 2 Slide 2 of 25
Pre-Opened Console Files Pre-opened I/O files available to Console-mode programs PInput < cin >> var; POutput < cout << exp; P Error reporting < cerr << exp; Pcin, cout, and cerr are library objects keyboard standard in stdin cin program screen standard error stderr cerr screen standard out stdout cout CS 1410 Chapter 2 Slide 3 of 25
The C/C++ Preprocessor Simple text manipulation P Traditionally, a program (cpp) that ran before the compiler < Functionality may be merged with modern compilers (-E terminates compilation after preprocessing a file) < Performs textual replacement before compilation begins P Processes directives that begin with # < #include <iostream> < and > indicate system header files (located in the include directory) < #include myprog.h " and " indicate program header files located in the current directory < #define line_length 100 nemonic for magic numbers and strings consistency (one place for change) CS 1410 Chapter 2 Slide 4 of 25
The Preprocessor In Action Substitutes and copies text #define SIZE 100 other stuff preprocessor iostream stuff compiler prog.h other stuff #include <iostream> #include "prog.h" using namespace std; void main( ) { cout << SIZE; } prog.cpp iostream void main( ) { cout << 100; } temporary file CS 1410 Chapter 2 Slide 5 of 25
Compiling Programs Multi-file programs source code compiler object files libraries editor linker executable runtime.cpp.c CS 1410 Chapter 2 Slide 6 of 25.obj.o
Basic Data Types Type Specifiers PData types < void 0 bytes no value < char 1 byte -128 to 127 or 0 to 255 < short 2 bytes -32,767 to 32,767 < int 2 to 4 bytes -2,147,483,648 to 2,147,483,647 < long 4 bytes -2,147,483,648 to 2,147,483,647 < bool int false / true < float 4 bytes ±3.4028234 10 ±38 (6-7 sig digs) < double 8 bytes ±1.79769313486231570 10 ±308 (~15 sd) < long double 16 bytes not universally supported P Ambiguities < The size of an int is the machine s word size < The only garentee is short # int # long < char is signed on some machines and unsigned on others P Most compilers use IEEE format for floating point numbers CS 1410 Chapter 2 Slide 7 of 25
Definitions and Declarations Important vocabulary terms P Definitions allocate memory < Variables: int counter; < Functions: double sqrt(double x) {... } P Declarations introduce a name, identifier, or symbol to the compiler (the name is placed in the compiler s symbol table) < Variables: extern int counter; < Functions: double sqrt(double x); // in <cmath> PA definition may also serve as a declaration CS 1410 Chapter 2 Slide 8 of 25
Type Conversions Implicit and Explicit Pchars and ints convert back and forth P Small types automatically promoted to large types in arithmetic expressions PIf a and b are ints, a/b is an int (truncates if necessary) P Explicit conversions are called type casts: (type)expression < Required to convert from a large type to a small type and to force conversions for / < int i = (int) 3.14159; // always truncates < int i = (int)(3.14159 + 2.7); < unsigned int i = (unsigned int) 75; < double x = (double) 1 / 3; CS 1410 Chapter 2 Slide 9 of 25
Identifier Names (i.e., Symbols) Variables, functions, structures, classes, etc. PRules < May be any length < Are case sensitive < Must begin with a letter, which includes an underscore (_) < Subsequent characters may be letters, digits, and underscores < Cannot be a keyword < May only be defined once in a scope < Should avoid library names < Must be declared before use < Must be defined exactly once CS 1410 Chapter 2 Slide 10 of 25
Expression and Statement Overview The Building Blocks - vocabulary terms P C++ is an imparative language PExpressions produce a value < Constant < Variable < Function call (returning a value not void) < Grouping of the above combined with operators < Form r-values (allowed on the RHS =): y + z or sqrt(y) or n > 100 PStatements form a complete unit of work are instructions < Are terminated with a semicolon (;) < May span lines or may be more than one on a line < Function call (not returning a value or value ignored) < Assignment statements: x = y + z; or p = sqrt(y); < Compound (or block) statements are formed of simple statements between { and } (block is not terminated with a semicolon) CS 1410 Chapter 2 Slide 11 of 25
Variables Name a region of memory where data is stored PMust be defined before use: includes data type and name P Names are case sensitive PExamples (definition and initialization) < int dollars; < int quarters, dimes, nickels, pennies; < int money = 217; < double x, pi = 3.14159; < char begin = 'A', end = 'Z', newline = '\n'; int i; i undefined 0x0a000010 i is unitialized i = 10; i 10 0x0a000010 i is 10 CS 1410 Chapter 2 Slide 12 of 25
Variables: Address vs Content Address is intrinsic, content may change PA left value (aka l-value) < is a value that can be on the left hand side of = < is the address of a variable PA right value (aka r-value) < is a value that can be on the right hand side of = < can be any valid expression i = // i represents the address of i (l-value or 0xffffff00) = i // i represents the content of i (r-value or 73) i 73 0xffffff00 CS 1410 Chapter 2 Slide 13 of 25
Variable Modifiers C/C++ Keywords P signed P unsigned P long P short Pauto Pstatic little used- turns unsigned char into signed char (the signedness of char is machine and/or implementation defined) no negative values (doubles the magnitude; often used with bit-manipulation operators; unsigned arithmetic does not overflow) long int is usually just called long short int is usually just called short never used except to illustrate that it can be used (i.e., auto is the default access specifier) local static variables maintain values between function invocation CS 1410 Chapter 2 Slide 14 of 25
Constants Types and Examples Pchar 'x' // single quote is a char P String "x" // double quote is a string P String "Hello World" Pint < Decimal 100-100 < unsigned int 123U < long int 10000000L < Octal 0377 unsigned only < Hexadecimal 0xff 0xFF unsigned only P float/double 3.13159 0.1 1.0.1 1. -6.68e-24 P long double 2.74e145L // uncommon P Explicit float 123.456F CS 1410 Chapter 2 Slide 15 of 25
Special Character Constants Backslash Characters P Digraphs represent a single character P\n new line P\t horizontal tab P\0 null (terminates strings) P\b back space P\f form feed P\r carriage return P\a alert (i.e., bell) P\" double quote P\' single quote P\\ backslash P\ddd octal number P\xff hexadecimal number P"Hello\tWorld\n" < The compiler automatically places a \0 after the \n CS 1410 Chapter 2 Slide 16 of 25
Operators Precedence and Associativity Operator [ ]., -> (dot and arrow) ( ) ++, --! ~ +, - ( ) & * sizeof Description indexing member selectio n function invocation auto increment and decrement logical negation bitwise complement unary grouping and casting address off indirection or dereference size of variable or type *, /, % multiplication, division, modulo º CS 1410 Chapter 2 Slide 17 of 25 Assoc º º º»»»»»»»»
Operators Continued +, - addition and subtraction º << >> bitwise left shift bitwise right shift (sign extend) <, >, <=, >= logical relationships º ==,!= logical equality or inequality º & bitwise and º ^ bitwise exclusive-or º bitwise or º && logical and º logical or º?: conditional expression º =, +=, -=, *=, /=, %=, <<=, >>=, &=, =, ^= operation and assignment (target must be a variable or l-value) CS 1410 Chapter 2 Slide 18 of 25 º º»
Operator Examples Unusual operators P Multiple assignment (i.e., the = operator returns a value) < i = j = k = 0; /* equivalent to i = (j = (k = 0)) */ < while ((c = getc( ))!= -1) P Auto increment and decrement < Target must be a variable (i.e., an l-value) < int i, j =10; < i = j++; /* i is 10, j is 11 */ < i = ++j; /* i is 11, j is 11 */ < i = j--; /* i is 10, j is 9 */ < i = --j; /* i is 9, j is 9 */ < i++, ++i, i--, and --i are legal (i.e., assignment is not required) < May be embedded in expressions < Often used in array indexes CS 1410 Chapter 2 Slide 19 of 25
Auto Increment / Decrement Understanding the shortcuts x = 10; Operator Meaning Result a = x++; a = x; a == 10 x = x + 1; x == 11 a = ++x; x = x + 1; a == 11 a = x; x == 11 a = x--; a = x; a == 10 x = x - 1; x == 9 a = --x; x = x - 1; a == 9 a = x; x == 9 CS 1410 Chapter 2 Slide 20 of 25
Operation with Assignment More unusual operators Pop= (+=, -=, *=, /=, %=, ~=, <<=, >>=) < variable op= expression; ø variable = variable op expression; < x += 10; ø x = x + 10; < i -= 2; ø i = i -2; < a /= b; ø a = a / b; < index %= size; ø index = index % size; < mask <<= 2; ø mask = mask << 2; CS 1410 Chapter 2 Slide 21 of 25
Comments Program documentation PC < /* comments go here */ < Can span lines PC++ < /* can use C style comments */ < // comments to the end of the line < Styles can be nested < I use C++ style and save C style to temporarily comment out code /* This style works well for large * commentary before functions */ // Function descriptions can // also be presented in this style /* void func( ) { a = b + c: } */ // comment CS 1410 Chapter 2 Slide 22 of 25
Test Cases and Program Validation The first step in test driven programming PA test case consists of at least two values: < Input value < Correct output value for the input < Long calculations may require one or more intermediate values PA set of test cases tests the behavior of the program with < Correct input < Incorrect input < Boundary values if appropriate Boundary values are on the boundary between correct and incorrect Many errors occur near or on boundary values double c = 5.0 / 9.0 * (f - 32); test cases: input: 32; output 0 input: 30; output: -1.111111 input: 212; output 100 input: 213; output: 100.555556 CS 1410 Chapter 2 Slide 23 of 25
Test Driven Programming AKA Test Driven Development PUnit tests < Are often but not always automated < They test the functionality of individual parts of a system PA unit test is a set of test cases P When practicing test driven programming / development, programmers create the unit test before writing any code PUnder what conditions can the code fail? P Programming is finished when the programmer cannot think of and test for any more failure conditions CS 1410 Chapter 2 Slide 24 of 25
Programming Style Only one rule: MAKE IT READABLE P Compiler ignores indentation and blank lines P Long statements may span multiple lines PMultiple statements may be placed on one line P Recomendations: < One definition / declaration per line < One statement per line < Keep lines short enough that they fit on the screen or printed page < Let physical layout reflect logical construction ( pretty printing ) < Use indentation consistently (use a single editor if possible) < Use blank lines to separate code into logical units; more space for more logically separated units < Place braces ( { and } ) consistently CS 1410 Chapter 2 Slide 25 of 25