C++ program structure Variable Declarations



Similar documents
Informatica e Sistemi in Tempo Reale

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Object Oriented Software Design

6. Control Structures

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Comp151. Definitions & Declarations

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

How to: Use Basic C++, Syntax and Operators

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Java Interview Questions and Answers

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

C++ Language Tutorial

Basics of I/O Streams and File I/O

While Loop. 6. Iteration

Object Oriented Software Design

Sources: On the Web: Slides will be available on:

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Chapter One Introduction to Programming

Passing 1D arrays to functions.

AP Computer Science Java Subset

An Incomplete C++ Primer. University of Wyoming MA 5310

Lecture 2 Notes: Flow of Control

The C Programming Language course syllabus associate level

Chapter 5 Functions. Introducing Functions

JavaScript: Control Statements I

C++ Essentials. Sharam Hekmat PragSoft Corporation

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

An Introduction to Assembly Programming with the ARM 32-bit Processor Family

I PUC - Computer Science. Practical s Syllabus. Contents

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Objective-C Tutorial

C++ INTERVIEW QUESTIONS

Statements and Control Flow

Member Functions of the istream Class

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

C++FA 3.1 OPTIMIZING C++

Answers to Review Questions Chapter 7

Syllabus OBJECT ORIENTED PROGRAMMING C++

Chapter 3 Operators and Control Flow

Conditions & Boolean Expressions

Fundamentals of Programming

Chapter 8 Selection 8-1

Keil C51 Cross Compiler

Parameter Passing. Standard mechanisms. Call by value-result Call by name, result

PL / SQL Basics. Chapter 3

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

A brief introduction to C++ and Interfacing with Excel

6.087 Lecture 2 January 12, 2010

Functions and Parameter Passing

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Chapter 2: Elements of Java

Moving from CS 61A Scheme to CS 61B Java

Example of a Java program

Pemrograman Dasar. Basic Elements Of Java

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Moving from C++ to VBA

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

J a v a Quiz (Unit 3, Test 0 Practice)

13 Classes & Objects with Constructors/Destructors

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Compiler Construction

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

C++FA 5.1 PRACTICE MID-TERM EXAM

Conditionals (with solutions)

MISRA-C:2012 Standards Model Summary for C / C++

CORBA Programming with TAOX11. The C++11 CORBA Implementation

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Introduction to Java

arrays C Programming Language - Arrays

ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters

Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

El Dorado Union High School District Educational Services

Computer Programming C++ Classes and Objects 15 th Lecture

PROGRAMMING IN C PROGRAMMING IN C CONTENT AT A GLANCE

Stacks. Linear data structures

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Selection Statements

VB.NET Programming Fundamentals

public static void main(string[] args) { System.out.println("hello, world"); } }

The programming language C. sws1 1

Windows PowerShell Essentials

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

5 Arrays and Pointers

URI and UUID. Identifying things on the Web.

An API for Reading the MySQL Binary Log

About The Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

C++ Crash Kurs. C++ Object-Oriented Programming

Chapter 2 Introduction to Java programming

C++ Programming Language

Transcription:

C++ program structure A C++ program consists of Declarations of global types, variables, and functions. The scope of globally defined types, variables, and functions is limited to the file in which they are declared. Definitions of one or more functions, one of the functions must be named main A C++ function definition consists of Declarations of locally defined types, variables, and functions. Executable statements Functions may not be nested Declarations and executable statements may be intermixed. Types, variables, and functions must be declared before they are referenced in statements. Variable Declarations Variable declarations have the form: type variable list ; variable list ::= variable variable, variable list Example int i, j, k; // Declares three integer variables: // i, j, and k float x, y; // Declares two floating variables: // x and y. string s; // Declares s to be of type string // (a library defined type) 2

Statements statement ::= labeled statement expression ; compound statement selection statement iteration statement jump statement declaration statement try-block 3 labeled statements labeled statements ::= identifier : statement case constant expression : statement default : statement The form identifier : statement is used as the target of the goto statement. The case and default forms are used within switch. 4

expression statement expression statement ::= expression ; ; In C++ assignment is an operator. Some other programming languages have an assignment statement. 5 compound statement compound statement ::= { statement list } statement list ::= empty statement list statement 6

selection statement selection statement ::= if ( expression ) statement if ( expression ) statement else statement switch ( expression ) statement In the if statement, an expression value of 0 is treated as false and a nonzero value is treated as true. If if statements are nested, the closest if is associated with an else. The statement following the switch ( expression ) is generally a compound statement containing statements which are labeled using the case constant expression : or default : form. (There may be only one default label.) The expression is evaluated and control is transferred to the statement whose case constant expression : equals the expression value. If none match, the statement is skipped. Flow of control otherwise passes over case constant expression : s. One must explicitly exit the scope of the switch statement via a break statement. 7 Example of C++ switch break after each case switch (n) { case 1: case 2: cout << "Buckle my shoe\n"; break; case 3: case 4: cout << "Shut the door\n"; break; case 5: case 6: cout << "Pick up sticks\n"; break; } 8

Example of C++ switch No break after case switch (i+1) { case 12: voice << "Twelve lords a-leaping;" << endl; case 11: voice << "Eleven ladies dancing;" << endl; case 10: voice << "Ten pipers piping;" << endl; case 9: voice << "Nine drummers drumming;" << endl; case 8: voice << "Eight maids a-milking;" << endl; case 7: voice << "Seven swans a-swimming;" << endl; case 6: voice << "Six geese a-laying;" << endl; case 5: voice << "Five golden rings;" << endl; case 4: voice << "Four calling birds;" << endl; case 3: voice << "Three French hens;" << endl; case 2: voice << "Two turtle doves, and" << endl; case 1: voice << "A partrige in a pear tree" << endl << endl; } 9 iteration statement iteration statement ::= while ( expression ) statement do statement while ( expression ) ; for ( for init statement expression-1 ; expression-2 ) statement expression-1 ::= empty expression expression-2 ::= empty expression 10

The for statement The statement for ( for init statement expression-1 ; expression-2 ) statement is logically equivalent to: for init statement while ( expression-1 ) { statement expression-2 ; } Generally, the for init statement will set a variable to an initial value, expression-1 will test to see that that variable has not reached its terminating condition, and expression-2 will increment (or decrement) the variable. 11 jump statement jump statement ::= break ; continue ; return ; return expression ; goto identifier ; A break must occur within either an iteration statement or a switch statement. It causes control to pass out of the iteration or switch statement. A continue must occur within an iteration statement. It causes control to pass to the end of the iteration statement and the next iteration to be executed. 12

The return statement, without an expression, returns control to the caller of a function that has a void return type. The return statement with an expression returns control to the caller of a function with the expression as the value of the function. 13 Exception Handling try-block ::= try compound statement handler-seq handler-seq ::= handler handler-seq-opt handler-seq-opt ::= empty handler-seq handler ::= catch ( exception-declaration ) compound statement exception-declaration ::= type-specifier-seq object name... throw-expression ::= throw assignment-expression-opt When a function detects an error, it should throw an exception. The function that calls this function (directly or indirectly) may catch the exception. If an exception is not caught, the program aborts. Exceptions are objects that may be of any type. The type-matching of a thrown exception to the catch is similar to the type-matching of a function call. A catch (...) will catch any exception, but not provide any information about the specific exception caught. A standard set of exceptions is defined in the header file <stdexcept>. 14

Expressions Expressions are of the general form operand 1 operator operand 2 or operator operand or operand operator Operands and operators are grouped from left to right according to the operator precedence. The depth of the operator in the syntax tree determines operator precidence. The following is an abbreviated syntax for C++ expressions. 15 name ::= identifier primary expression ::= literal name ( expression ) post-fix expression ::= primary expression post-fix expression ( expression list opt ) post-fix expression [ expression ] post-fix expression. member name post-fix expression -> member name post-fix expression ++ post-fix expression -- expression list opt ::= empty expression list expression list ::= assignment expression expression list, assignment expression unary expression ::= post-fix expression ++ unary expression -- unary expression unary operator cast expression unary operator ::= + - ~! * & cast expression ::= unary expression ( type name ) cast expression pm expression ::= cast expression 16

multiplicative expression ::= pm expression multiplicative expression * pm expression multiplicative expression / pm expression multiplicative expression % pm expression additive expression ::= multiplicative expression additive expression + multiplicative expression additive expression - multiplicative expression shift expression ::= additive expression shift expression << additive expression shift expression >> additive expression relational expression ::= shift expression relational expression < shift expression relational expression > shift expression relational expression <= shift expression relational expression >= shift expression 17 equality expression ::= relational expression equality expression == relational expression equality expression!= relational expression and expression ::= equality expression and expression & equality expression exclusive-or expression ::= and expression exclusive-or expression ^ and expression inclusive-or expression ::= exclusive-or expression inclusive-or expression exclusive-or expression logical-and expression ::= inclusive-or expression logical-and expression && inclusive-or expression logical-or expression ::= logical-and expression logical-or expression logical-and expression conditional expression ::= logical-or expression logical-or expression? expression : conditional expression 18

assignment expression ::= conditional expression unary expression assignment operator assignment expression assignment operator ::= = *= /= %= += -= >>= <<= &= ^= = expression ::= assignment expression expression, assignment expression 19 The form post-fix expression ( expression list opt ) is known as the function call. C++ a function may be an expression. The form post-fix expression [ expression ] is known as the array access operation, which will be discussed later. The forms post-fix expression. member name and post-fix expression -> member name access members of classes, which will be discussed later. The forms post-fix expression ++ and post-fix expression -- are post increment (decrement). The value is the value of post-fix expression but there is a side-effect that the post-fix expression is incremented (decremented) by one. post-fix expression must be what is known as a modifiable l-value. I.E. it must be capable of being the target of an assignment. 20

The forms ++ unary expression and -- unary expression are pre increment(decrement). The value is the value of unary expression incremented (decremented) by one. There is also the side effect that the unary expression is incremented (decremented) by one. unary expression must be what is known as a modifiable l-value. I.E. it must be capable of being the target of an assignment. The unary operator + has no effect; - returns the arithmetic negative; ~ the bit-wise complement, and! the logical complement. (! turns a zero into a non-zero value and a non-zero value into a zero). The unary operator * is used to de-reference a pointer. (More on pointers later.) The unary operator & is used to create a pointer value. 21 The form: cast expression ::= unary expression ( type name ) cast expression has the effect of either forcing a type conversion or having the cast expression interpreted as the type type name. While still part of the language, its use is discouraged. The following are the new cast operators: static_cast < type-id > ( expression ) Convert the expression to the specified type, if there is a conversion defined. reinterpert_cast < type-id > ( expression ) The raw bits are reinterpreted to represent the specified type. The results are computer and compiler implementation specific. Should be used with caution and desperation. dynamic_cast < type-id > ( expression ) This will be discussed after polymorphism is introduced. const_cast < type-id > ( expression ) Can be used to change the const status of the expression. 22

The forms: multiplicative expression ::= pm expression multiplicative expression * pm expression multiplicative expression / pm expression multiplicative expression % pm expression additive expression ::= multiplicative expression additive expression + multiplicative expression additive expression - multiplicative expression % is the modulus operator. The operators << and >> are the left shift and right shift respectively. The operands must be integers. They are also known as the insertion and extraction operators when applied to I/O streams. The forms equality expression ::= relational expression equality expression == relational expression equality expression!= relational expression logical-and expression ::= inclusive-or expression logical-and expression && inclusive or expression logical-or expression ::= logical-and expression logical-or expression logical-and expression 23 The forms: and expression ::= equality expression and expression & equality expression exclusive-or expression ::= and expression exclusive-or expression ^ and expression inclusive-or expression ::= exclusive-or expression inclusive-or expression exclusive-or expression perform bit-wise operations. Care must be taken in using & vs. && and vs.. The form: logical-or expression? expression : conditional expression Its value is the value of expression (the second operand) if logical-or expression (the first operand) is true and conditional expression (the third operand) if logical-or expression is false. 24

The form unary expression = assignment expression is the same as the assignment statement in other languages. The left hand side must be what is known as a modifiable l-value. I.E. it must be capable of being the target of an assignment. The value is the value of assignment expression. While other operations of equal precidence are associated from left to right, the assignment operators are associated from right to left. Thus assignments may be nested or chained such as i = j = k = 0; which is equivalent to (i = (j = (k = 0))); and has the effect of setting all of the variables to 0. The form unary expression operator = assignment expression is equivalent to unary expression = unary expression operator assignment expression where operator is * / % + - >> << & ^ or I.E. x /= 5; is the same as x = x / 5 25 Fundamental Types The fundamental (built-in) types are as follows: C++ Type bool Meaning The logical values true and false. There is an implicit conversion from all non-zero numeric values or non-null pointers to true, and all zero numeric values or null pointers to false. char The character set recognized by the computer; generally 8-bit bytes. May be either unsigned or signed. unsigned char The character set recognized by the computer; generally 8-bit bytes. Explicitly treated as an un-signed value. signed char The character set recognized by the computer; generally 8-bit bytes. Explicitly treated as a signed value. int The integers. Range is implementation defined. Generally either 16 or 32 bits. short The integers. Generally 16 bits. May also be written as short int. long The integers. Generally 32 bits. May also be written as long int. 26

C++ Type Meaning unsigned short The integers treated as an unsigned value. Generally 16 bits. May also be written as unsigned short int. unsigned long The integers treated as an unsigned value. Generally 32 bits. May also be written as unsigned long int. float Floating point or real arithmetic values. double Double precision floating point. long double Extended double precision floating point. 27 Form: return type function name (); Example: void skip_three(); Function Declarations (functions without arguments) Declares the function skip_three as taking no arguments and returning no value. Function Call (functions without arguments, and returning no value) Form: function name (); Example: draw_circle(); Initiates the execution of the function. After the function has finished, the next statement in the parent function will be executed. 28

Function Definition (functions taking no arguments) return type function name () { statement list } Example: void draw_triangle() { // Draw a triangle. draw_intersect(); draw_base(); } // end draw_triangle 29 Draw Stick Figure // FILE: StkFigMn.cpp // DRAW A STICK FIGURE (Main Function Only) // Functions used... // DRAWS A CIRCLE void draw_circle(); // DRAWS A TRIANGLE void draw_triangle(); // DRAWS INTERSECTING LINES void draw_intersect(); int main() { // Draw the figure. // Draw a circle. draw_circle(); // Draw a triangle. draw_triangle(); // Draw intersecting lines. draw_intersect(); return 0; } 30

IXQFWLRQPDLQ // FILE: StkFigMn.cpp // DRAW A STICK FIGURE (Main Function Only) // Functions used... // DRAWS A CIRCLE void draw_circle(); // DRAWS A TRIANGLE void draw_triangle(); // DRAWS INTERSECTING LINES void draw_intersect(); int main() { // Draw the figure. // Draw a circle. draw_circle(); // Draw a triangle. draw_triangle(); // Draw intersecting lines. draw_intersect(); return call IXQFWLRQGUDZBFLUFOH // FILE: DrawCir.cpp // DRAWS A CIRCLE #include <iostream.h> void draw_circle() { cout << " * " << endl; cout << " * *" << endl; cout << " * * " << endl; } // end draw_circle } return 0; 31 Function Declaration (functions taking arguments) Form: return type function name ( formal argument type list ); argument list is a list of zero or more formal argument s separated by commas. formal argument ::= type type argument name default value default value ::= empty = expression Normally only the type is declared unless a default value is specified. Arguments with default values must be specified after arguments without. Example: int max(int, int, int); Declares the function max as taking a three integer values and returning an integer result. 32

Function Call (functions with arguments) function name ( actual argument list ) actual argument list is a list of zero or more expression s separated by commas. There must be one actual argument for each formal argument which does not have a default value specified. The type of each actual argument must correspond to each formal argument. The value of this expression is the result returned by the function. The types of the expressions in the actual argument list must correspond (or be convertible to) the types in the formal argument list. Example a = max(1, 3, 2); will get the value of 3 and assign it to a. 33 Function Definition (functions taking arguments) return type function name ( formal argument list ){ function body } argument list is a list of zero or more formal argument s separated by commas. formal argument ::= type type argument name default value Example: int max (int x, int y, int z) { int m = (x > y)? x : y; return (m > z)? m : z; } 34

Steps in a Function Call 1. Each expression in actual argument list is evaluated. 2. The declarations of the formal argument list are executed with each of its corresponding actual argument as the initial value. 3. The function body is executed. 4. The return value becomes the value of the function call expression. Example: a = max(1, 3, 2); Is equivalent to int x = 1, y = 3, z = 2; int m = (x > y)? x : y; a = (m > z)? m : z; Observe that the values of the actual argument s are copied into the corresponding formal argument s. 35 References A declaration of the form: type & identifier1 = identifier2 Declares that identifier1 is a reference to identifier2. Effectively identifier1 becomes an alias for identifier2. Used mostly in functions. Example: void compute_sum_ave (float num1, // IN: values used in compuation float num2, float& sum, // OUT: sum of num1 and num2 float& average) // OUT: average of num1 and num2 { sum = num1 + num2; average = sum / 2.0; } 36

The expression: compute_sum_average(x, y, s, m); is equivalent to: float num1 = x, num2 = y; float& the_sum = s; float& average = m; the_sum = num1 + num2; average = the_sum / 2.0; Observe that the values of the actual arguments corresponding to num1 and num2 (x and y) are copied into these variables for the duration of the function execution. On the other hand, the names sum and average take the place of the corresponding actual arguments (s and m). 37 calling function data area compute_sum_ave data area x 8.0 y 10.0 s? m? value of x copied into num1 value of y copied into num2 reference to s stored in sum reference to m stored in average num1 num2 sum average 38

// FILE: MkChange.cpp // DETERMINES THE NUMBER OF UNITS OF CHANGE OF A PATICULAR // DENOMINATION TO DISPENSE WHEN MAKING CHANGE void make_change (int change_denom, // IN: denomination in // which change is // to be returned int& change_needed, // INOUT: amount for which // change is needed int& num_units) // OUT: number of units // of specified // denomination to // be returned // Pre: Change_denomination > 0 and change_needed >= 0 // Post: Num_units is the number of units of change to // dispense and change_needed is reduced by the // amout given. { num_units = change_needed / change_denom; change_needed = change_needed - (num_units * change_denom); return; } // end of make_change 39 // FILE: MakChng.cpp // DRIVER PROGRAM FOR make_change #include <iostream> #include <string> void make_change(int, int&, int&); int main() { float change; int pennies; int num; int denoms[] = {2000, 1000, 500, 100, 25, 10, 5, 1}; std::string names[] = {"twenties", "tens", "fives", "ones", "quarters", "dimes", "nickels", "pennies"}; for (;;){ // Loop forever std::cout << "Enter amount (0 terminates) "; std::cin >> change; if (change == 0.0) break; // exit loop pennies = int(change * 100.0 + 0.5); for (int i = 0; i < 8; i++){ make_change(denoms[i], pennies, num); if (num!= 0) std::cout << num << ' ' << names[i] << std::endl; } // end for loop } // end loop forever return 0; } 40

The main program A program is invoked by the operating system. This can be as a result of a command issued to the shell, clicking an icon on the window desk-top, or from another program, such as the a GUI development environment. The operating system creates a run-time environment and then transfers control to a pre-defined entry point. For C++ programs, this pre-defined entry point is an implementation and operating system specific program that calls the function main. When main returns, this program passes the return value from main back to the operating system. A return value of 0 is considered a normal return, and a non-zero value is considered an error return. The function main can be in one of two forms: int main () { /* */ return 0;} or int main (int argc, char* argv[]){ /* */ return 0;} In the second form, argc is the count of the number of arguments, and argv is an array of pointers to char that are the arguments themselves. There is always at least one argument, which is the name of the program. Arguments are either specified on the command line, or they may be defined for the window icon, or passed as part of an operating system call from a GUI. 41 For example, the g++ compiler may be invoked as follows: g++ -o hello hello.cpp Since g++ is a c++ program, its main function will be called, in this example, with the following: argc 4 argv[0] "g++" argv[1] "-o" argv[2] "hello" argv[3] "hello.cpp" 42