Home

C++ Programs

C++ Programs

 

 

C++ Programs

ENGN 38
Introduction to Computing for Engineers
Chapter 3:  Functions

 

C++ Programs are composed of different parts that do one of the following:

  • Input

  • Processing

  • Output

In C++ these parts should be performed by functions. 

In C++ all procedure-like entities are called functions. 
Other languages have other terminology:

  • Procedures

  • Subprograms

  • Subroutines

  • Methods

  • Modules

 

Functions are very important in C++

  • They modularize a program.  (I/P/O)

  • They are reusable and so reduce redundancy. 
    If you know that you will be doing the same thing again and again, create a function.

  • They enable information hiding
    i.e. someone can know how to use a function without really knowing the details of how it works.  This is good for proprietary purposes and also just to keep someone from messing with your code.

 

The function main should be a very short and simple program that just makes function calls

int main()

{

   variable declarations ;

   input function invocation ;

   processing function invocation;

   output function invocation ;

   return 0;

}


Functions in C++

In C++ there are two types of functions:

    1. valued functions – returns a single value and may or may not performs action(s)
    2. void functions – does not return a value, but performs some kind of action(s) such as output to the screen or giving a value to a variable. 

Syntax to invoke a function:      functionName ( argument1, argument2…)

 

To use the function you need to know:

  • the name of the function
  • the number, order and datatype of the required arguments
  • the data type of the returned value, if any, and its relationship to the input
  • any actions the function performs

All this information is called the interface of the function.
It allows you to use the function without having to understand how it works!

 

You don’t need to understand what happens inside the black box! 
What goes on inside the box is called the implementation of the function.
It is actually the code that enables the function to do what it is supposed to do.
The implementation is separate from the ability to use it. 
This is called information hiding or procedural abstraction or encapsulation.

 

 

Note that in C++ functions can:

  • return a value or not
  • have arguments or not
  • perform actions or not.

And any combination of these things!        


Using functions in C++
To invoke, call, use, or reference a function you just write the name and then the argument list inside parentheses separated by commas.

A valued function is invoked in any expression where you want to use the value that the function returns.
So usually a valued function is invoked in the context of an assignment statement.
y = 12 * sin(45);
z = sqrt (10);

A void function is invoked whenever you want the actions executed that the function will perform.
So usually a void function is invoked by itself as an executable statement:
printName(“Wendy”);
showResults();

 

Pre-defined functions in C++
In C++ there are pre-defined functions and programmer-defined functions. The predefined functions are stored in some library and so your program must contain an include directive for the library that the function is in. (The Appendix of the textbook lists some of the pre-defined functions in C++.)

e.g. sqrt function is in the cmath library so you would need this preprocessor directive:
#include <cmath>

Usually the definitions for predefined functions are normally placed in the standard namespace and so your program also must contain the appropriate using directive:
using namespace std;


Examples of C++ pre-defined valued functions:
sqrt(4.0)                                 // found in <cmath>
pow(3,5)                                 // found in <cmath>   
abs(2) for ints                         // found in <cstdlib>
labs(2.000) for longs                          // found in <cstdlib>
fabs(2.0) for doubles                          // found in <cmath>
floor(4.5)                                // found in <cmath>
exit(2)                                     // found in <cstdlib>
rand()                                      // found in <cstdlib>
Valued functions are used anywhere you need the value that the function returns.

Note that rand is an interesting function.
It takes no arguments but returns a value! It is a random number generator. It returns a random number, i.e. the value returned is not determined by its arguments or anything else for that matter.  It is random!
The value returned is in the range of 0 to RAND_MAX inclusive where the constant RAND_MAX is also found in <cstdlib>. It is usually = 32767.

To get a random number between 0 and 10:
rand() % 11  this is called scaling

To get a random number between 0 and 100:
(RAND_MAX – rand() ) / static_cast<double>(RAND_MAX)

To get a random number between 5 and 10:
( 5 + (rand() % 6 ) )

Note that rand actually returns a pseudorandom int.  i.e. it seems random but actually is not.
Why isn’t rand() a true random number generator? 
Because the numbers it generates are not truly random. 
They are determined by a seed.  This seed is set by the function srand which is also found in <cstdlib>. 
The same system will generate the same sequence of random numbers for the same seed.
That is why rand is not a true random number generator.
srand is a void function

Examples of C++ pre-defined VOID functions:
exit(int);
srand(unsigned int);
These perform action(s) – they do not return a value.

The exit function does two things:

  1. gives control back to the OS
  2. gives the value of the int argument to the exit status variable of the OS

1 is commonly used for error-incurred exits.
0 is used for normal exits to the function.

The srand function does just one action: It sets the seed for the rand() function to the unsigned int argument.

 

Programmer defined functions
Programmer defined functions are used in the same way as predefined functions.
They can be valued or void, take arguments or not, perform actions or not.

A programmer can define functions in a separate file (as the predefined functions are) or in the same file as main (as we will do).

The description of a programmer-defined function contains two parts:
the interface and the implementation

  • function declaration or function prototype
    This is the interface of the function.
    This is everything you need to know in order to use the function.  i.e. the name of the function, the number, type and order of the required arguments, what the function returns (if anything) and how it relates to the input, and/or the actions the function performs. 
  • function definition
    This is the implementation of the function.

Syntax for function declaration:
                        int        round   (double param1, char param2);
 



data type of value returned    name of function    types and order of required arguments to the function

param1 and param2 are called (formal) parameters.  Consider them as placeholders. When the function is invoked, the formal parameters in the function body will be replaced by the arguments in the function call. The names are not required in the prototype.

The actual int value returned by the function is determined by the function definition.
Note that this declaration (interface) gives almost all the information needed for the interface!
What doesn’t it give?
How can we include this missing information in the interface? (Answer: comments!)

Preconditions/Postconditions
The function declaration should have enough information so that a programmer is able to use the function just by looking at the declaration. They should not have to look at the function definition. 
So the prototype should include comments that explain exactly what the function does.

These comments should be divided into two parts:

  1. Preconditions
    These should explain what the function needs in order to be called and executed properly.
    e.g. are what type of variables does the function require as arguments? 
  2. Postconditions
    These should explain the results of the function call.
    e.g. the value returned and/or any actions performed by the function.

 
Sometimes if the only postcondition is the value the function returns, the word is omitted.
Some programmers omit the words Preconditions and Postconditions altogether.

You should think of the function call as the results described in the postconditions. 
This is much easier than thinking of the code.
This is the Principle of Procedural Abstraction = Black Box Principle = Information Hiding

Syntax for the function definition:
int  round  (double parm)

return (floor(parm + 0.5)) ;
//parentheses are not required
}                                             //for void functions it is just return;

The first line is the function header
It is like the function declaration except here the parameter names are required. 
Also there is no ; at the end.
The part in {} is the function body.
It has the code that makes the function work. 

Either the complete function definition or the function prototype must appear before the function is invoked.

You can have function calls to other functions inside function definitions.
You cannot have a function definition inside another function definition.


What happens when a function is invoked?
(You should memorize these steps!)

  • Program control goes to the function definition.
  • The parameters in the function definition are declared as variables local to the function.
    Additionally the values of these variables are initialized to the value of the arguments.
  • The statements in the function body are executed.
  • The function call ends when the return statement is executed.
    • If it is a valued function then the return statement returns a value to the place where the function was called.
    • If it is a void function then the return statement just returns control back to the place where the function was called.

A C++ program file usually follows this format:
preprocessor directives;
using directives;

declaration of global constants;

function declarations;

int main()
{
variable declarations;

   input function invocation;
processing function invocation;
output function invocation;

   return 0;
}

function definitions

The function main
Now you can see that main is just a function definition!
The function returns an int.  It takes no arguments.
It gets called by the OS automatically when your program is run. 
The return statement at the end causes control to go back to the OS.

  • The 0 goes into the exit status variable (part of the OS).
  • The return statement is not required by all compilers.
  • If the program exits unexpectedly, you should return 1;

Scope of a variable
The scope of a variable or constant refers to where the variable or constant is declared and available.

Nested blocks {{ }}
Variables are only available to the block that they are declared in.
So variables declared in an outer block are only available to that outer block.
So variables declared in an inner block are only available to that inner block.

Local Constant and Local Variables
Since a variable is available only in the block in which it is declared, we say that its scope is local to the block. It is not defined or available outside the block.

e.g. a function body is a block. So functions have local variables that are distinct from those outside the function, even if they have the same name as a variable in another block, such as main.

Global Constants and Global Variables
If a constant is declared outside main at the beginning of the program then it is a global named constant.  It can be used in any function definition that follows it.

You can also declare variables as global, but you shouldn’t. 
If you do, then you won’t be able to reuse the name in a function definition.


 


SOME FUNCTION EXAMPLES

Here is a function that rounds doubles to the nearest int:
function prototype:
int round (double number);                            // number is not required
function definition:
int round (double number)                             // note no semicolon at the end
{  
return static_cast<int>(floor ( number + 0.5));
}

 

A function that outputs 2 values:
function prototype:
void showResults (double x, double y);        // x and y are not required
function definition:
void showResults (double x, double y)

cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2); 

cout << x << endl << y << endl ;
return;                                                        // most compilers don’t require this
}                                                                    
/*note:  this function doesn’t return a value it just performs the actions of outputting the values of the arguments to the screen*/

 

A function that is friendly:
function prototype:
void Friendly ();        
function definition:
void Friendly ()

cout << “\nHi. I hope that you are having a nice day!\n”;
return;                                                       // this function did not return a value
}                                                                     // nor did it require any arguments!

 

 

 

 

Source: https://fog.ccsf.edu/~wkaufmyn/ENGN38/Course%20Handouts/03_Cpp_Functions.doc

Web site to visit: https://fog.ccsf.edu/

Author of the text: indicated on the source document of the above text

If you are the author of the text above and you not agree to share your knowledge for teaching, research, scholarship (for fair use as indicated in the United States copyrigh low) please send us an e-mail and we will remove your text quickly. Fair use is a limitation and exception to the exclusive right granted by copyright law to the author of a creative work. In United States copyright law, fair use is a doctrine that permits limited use of copyrighted material without acquiring permission from the rights holders. Examples of fair use include commentary, search engines, criticism, news reporting, research, teaching, library archiving and scholarship. It provides for the legal, unlicensed citation or incorporation of copyrighted material in another author's work under a four-factor balancing test. (source: http://en.wikipedia.org/wiki/Fair_use)

The information of medicine and health contained in the site are of a general nature and purpose which is purely informative and for this reason may not replace in any case, the council of a doctor or a qualified entity legally to the profession.

 

C++ Programs

 

The texts are the property of their respective authors and we thank them for giving us the opportunity to share for free to students, teachers and users of the Web their texts will used only for illustrative educational and scientific purposes only.

All the information in our site are given for nonprofit educational purposes

 

C++ Programs

 

 

Topics and Home
Contacts
Term of use, cookies e privacy

 

C++ Programs