CS201-25 - Introduction to Programming Lecture 25...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Introduction to Programming Lecture 25 Introduction to C++ language In Coming Lectures – – – C++ Features Classes Object Today’s Lecture Default Function Arguments Inline Functions Classes Rules for Structured Programming Do Modular programming – Write small function – Every function should perform a specific well defined task Function should obey single entry single exit rule Liberally Comment the code Object Oriented Language Early 1980's Bjarne Stroustrup at Bell Labs C with Classes C++ Java Default Function Arguments power ( x , n ) ; void f ( int i , double x ) ; void f ( int i =1 , double x = 10.5 ) { ­­ } Example 1 void f ( int i = 1 , double x = 10.5 ) { cout<<“i = ”<<i; cout<<“ x = “<< x<<endl; } main ( ) { f ( ) ; f ( 2 ) ; f ( 2 , 12 ) ; } Example 1 Output i = 1 x = 10.5 i = 2 x = 10.5 i = 2 x = 12 void f ( double x=10.5 , int i ) ; The declaration of variables inside the code while ( condition ) { // body of the while loop } { } int i ; ­­­ Scope of Variable When you declare a variable inside the block then the variable exists in that block. for ( int i = 0 ; i < 3 ; i++ ) { int temp = 22 ; cout << "\n i = " << i << "temp = " << temp ; } cout << "i = " << i ; Example 2 Inline functions inline #define SQUARE ( X ) X * X main ( ) { int i = 5 , j = 10 , k ; : i + j * i + j ; k = SQUARE ( i + j ) ; } Example 2 #define SQUARE ( X ) ( X ) * ( X ) main ( ) { int i = 5 , j = 10 , k ; ( i + j ) * ( i + j ) ; k = SQUARE ( i + j ) ; } Example 3 #define MAX ( A , B ) ( ( A ) > ( B ) ? ( A ) : ( B ) ) inline f ( int a, int b ) { if ( a > b ) return a ; return b ; } void main ( ) { int i , x , y ; x = 23 ; y = 45 ; i = MAX ( x++ , y++ ) ; // Side ­ effect : larger value incremented twice cout << "x = " << x << " y = " << y << '\n' ; x = 23 ; y = 45 ; i = f ( x++ , y++ ) ; // Works as expected cout << "x = " << x << " y = " << y << '\n' ; } Example 3 Function Overloading Operator Overloading Overloading Using the same name to perform multiple tasks or different task depending on the situation double Intsquareroot ( int i ) ; double Doublesquareroot ( double x ) ; int squareroot ( int i ) { // body of the function } Example 4 double squareroot ( double x ) { // body of the function } main ( ) { double i , x ; int j = 5 , k ; i = squareroot ( 10.5 ) ; cout << i << endl ; k = squareroot ( j ) ; cout << k << endl ; } Example 4 F ( int a , int b ) ; F ( int a , int b , int c ) ; Example main ( ) { ­­­­­­­­­­­ F ( 1 , 2 ) ; // F ( int a , int b ) ; is called F ( 1 , 2 , 3 ) ; // F ( int a , int b , int c ) ; is called ­­­­­­­­­­­ } int f ( int a ) ; double f ( int a ) ; Name Mangling ...
View Full Document

Ask a homework question - tutors are online