|< Let Have A Break! | Main | C & C++ Functions 2 >| Site Index | Download |


 

 

 

 

 

 

MODULE 4: C AND C++ FUNCTIONS 1

Receive nothing, return nothing-receive nothing, return something-
receive something, return something-receive something, return nothing
And they do something.  That is a function!

 

 

 

 

 

 

 

 

 

My Training Period: xx hours

 

Note:  Function is one of the important topics in C and C++. The source code for this Module is: C/C++ functions source codes and the lab worksheets for your practice: Function lab worksheet 1, lab worksheet 2, lab worksheet 3 and lab worksheet 4.

 

The C and C++ skills that supposed to be acquired:

 

  • Able to understand and use function.

  • Able to create user defined functions.

  • Able to understand Structured Programming.

  • Able to understand and use macro.

  • Able to appreciate the recursive function.

  • Able to find predefined/built-in standard and non-standard functions resources.

  • Able to understand and use predefined/built-in standard and non-standard functions.

  • Able to understand and use the variadic functions.

 

4.1   Some Basic Definition

 

  • Most computer programs that solve real-world problem are large, containing thousand to million lines of codes and developed by a team of programmers.

  • The best way to develop and maintain large programs is to construct them from smaller pieces or modules, each of which is more manageable than the original program.

  • These smaller pieces are called functions.  In C++ you will be introduced to Class, another type smaller pieces construct.

  • The function and class are reusable.  So in C / C++ programs you will encounter and use a lot of functions.  There are standard (normally called library) such as maintained by ANSI C / ANSI C++, ISO/IEC C, ISO/IEC C++ and GNU’s glibc or other non-standard functions (user defined or vendors specific or implementations or platforms specific).

  • If you have noticed, in the previous Modules, you have been introduced with many functions, including the main().  main() itself is a function but with a program execution point.

  • Functions are very important construct that marks the structured or procedural programming approach.

  • In general terms or in other programming languages, functions may be called procedures or routines and in object oriented programming, methods may be used interchangeably with functions.

  • Some definition: A function is a named, independent section of C / C++ code that performs a specific task and optionally returns a value to the calling program.

  • So, in a program, there are many calling function (caller) and called functions (normally called callee).

  • There are basically two categories of function:

  1. Predefined functions - available in the C / C++ standard library such as stdio.h, math.h, string.h etc.  These predefined functions also depend on the standard that you use such as ANSI C, ANSI C++, ISO/IEC C, Single UNIX Specification, glibc (GNU), Microsoft C etc. but the functions name and their functionalities typically similar.  You have to check your compiler documentation which standard that they comply to.

  2. User-defined functions – functions that the programmers create for specialized tasks such as graphic and multimedia libraries, implementation extensions or dependent etc.  This is non-standard functions normally provided in the non-standard libraries.

 

  1. A function is named with unique name - By using the name, the program can execute the statements contained in the function, a process known as calling the function.  A function can be called from within another function.

  2. A function performs a specific task - Task is a discrete job that the program must perform as part of its overall operation, such as sending a line of text to the printer, sorting an array into numerical order, or calculating a cube root, etc.

  3. A function is independent - A function can perform its task without interference from or interfering with other parts of the program.  The main program, main() also a function but with an execution point.

  4. A function may receive values from the calling program (caller) - Calling program can pass values to function for processing whether directly or indirectly (by reference).

  5. A function may return a value to the calling program - When the program calls a function, the statements it contains are executed.  These statements may pass something back to the calling program.

// demonstrates a simple function

// calling predefined functions needed in this program such as printf()

#include <stdio.h>

 

// function prototype, explained later

long cube(long);

 

void  main()

{

       long  input, answer;

       printf("\n--Calculating cube volume--\n");

       printf("Enter a positive integer, for cube side (meter):   ");

       scanf("%d", &input);

       // calling cube() function, bringing an input argument. main() is a caller

       answer  =  cube(input);

       // %ld is the conversion specifier for a long integer, more on this in another module

       printf("\nCube with side %ld meter, is %ld cubic meter.\n", input, answer);

}

 

// function definition, calculating cube's volume

// receive one argument that is cube's side (x), and supposed to return long type, this is a callee

long  cube(long x)

{

       // local scope (to this function) variable, only effective in this function 'body'

       long     x_cubed;

       // do the volume calculation

       x_cubed  =  x * x * x;

       // return a result to caller

       return     x_cubed;

}

 

Output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

C/C++ functions

C C++ functions

      C C++ functions

4.2    How A Function Works

C C++ functions

 

Arrow

Means

Calling function with data (argument) if any

Return to the next statement or execution with data if any

4.3    A Function Definition

long cube(long x)

{

       // local scope (to this function) variable, only effective in this function 'body'

       long     x_cubed;

       // do the volume calculation

       x_cubed  =  x * x * x;

       // return a result to caller

       return     x_cubed;

}

4.4    Structured Programming

  1. It is easier to write a structured program - Complex programming problems or program are broken into a number of smaller, simpler tasks.  Every task can be assigned to a different programmer and/or function.

  2. It’s easier to debug a structured program - If the program has a bug (something that causes it to work improperly), a structured design makes it easier to isolate the problem to a specific section of code.

  3. Reusability - Repeated tasks or routines can be accomplished using functions.  This can overcome the redundancy of code writing, for same tasks or routines, it can be reused, no need to rewrite the code, or at least only need a little modification.

A Very Simple Example

  1. Enter new names and address.

  2. Modify existing entries.

  3. Sort entries by last name.

  4. Printing mailing labels.

  1. Read the existing address list from disk.

  2. Prompt the user for one or more new entries.

  3. Add the new data to the list.

  4. Save the updated list to disk.

  1. Read the existing address list from disk.

  2. Modify one or more entries.

  3. Save the updated list to disk.

C C++ function and structured programming

 

 

4.4.1    A Top-down Approach

4.5    Writing A Function

4.5.1    The Function header

C/C++ function header

  1. Function return type - Specifies the data type that the function should returns to the calling program.  Can be any of C/C++ data types: char, float, int, long, double etc.  If there is no return value, specify a return type of void.  For example,

 

int     calculate_yield()        // returns a int type

float   mark()                        // returns a float type

void    calculate_interest( // returns nothing

  1. Function name - Can have any name as long as the rules for C / C++ variable names are followed and must be unique.

  2. Parameter list - Many functions use arguments, the value passed to the function when it is called.  A function needs to know what kinds of arguments to expect, that is, the data type of each  argument.  A function can accept any of C / C++ basic data types.  Argument type information is provided in the function header by the parameter list.  This parameter list just acts as a placeholder.

void myfunction(int x, float y, char z)

void yourfunction(float myfloat, char mychar)

int  ourfunction(long size)

long thefunction(void)

void testfunct(void)

int  zerofunct()

// demonstrate the difference between arguments and parameters

// using predefined functions in the C standard library

#include <stdio.h>

 

// main() function

void  main()

{

     float  x = 3.5, y = 65.11, z;

     // function prototype is here, a rare implementation...

     float  half_of (float);

     // In this call, x is the argument to half_of().

     z = half_of(x);

     printf("The function call statement is z = half_of(x)\n");

     printf("where x = 3.5 and y = 65.11...\n\n");

     printf("Passing argument x\n");

     printf("The value of z = %f \n", z);

     // In this call, y is the argument to half_of()

     z = half_of(y);

     printf("\nPassing argument y\n");

     printf("The value of z = %f \n\n", z);

}

 

// function definition, must receive one float value that will be placed in

// k and must return a float value back to the caller...

float    half_of(float  k)

{

     // k is the parameter, a placeholder.  Each time half_of() is called,

     // k may has different value that was passed as an argument.

     return  (k/2);

}

 

Sample output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

---------------------------------------------------------------------

C/C++ function arguments and parameters

 

C/C++ function arguments and parameters

C/C++ function arguments and parameters

C/C++ function overall structure

 

4.5.2    The Function Body

int function1(int y)

{

Int    a, b=10;      // local variable  

Float  rate;         // local variable

Double cost=12.55;   // local variable, been initialized

}

C/C++ function body and return value

 

Output:

 

C/C++ function body and return value console output

 

#include …

 

/* function prototype */

int funct1(int);

 

int main()

{

     /* function call */

     int y = funct1(3);

     …

}

 

/* Function definition */

int funct1(int x)

{…}

#include …

 

/* declare and define */

int funct1(int x)

{

   …

}

 

int main()

{

   /* function call */

   int y = funct1(3);

   …

}

  1. To use a variable in a function, the programmer must declare it in the function header or the function body.

  2. For a function to obtain a value from the calling program (caller), the value must be passed as an argument (the actual value).

  3. For a calling program (caller) to obtain a value from function, the value must be explicitly returned from the called function (callee).

4.5.3    The Function Statements

4.5.4    Returning A Value

C C++ function return value

// using multiple return statements in a function

#include <stdio.h>

 

// a function prototype, a mandatory in C++

int larger_of(int, int);

 

// a caller

void main()

{

       int x, y, z;

       puts("Enter two different integer values,");

       puts("separated by space. Then press Enter key: ");

       scanf("%d%d", &x, &y);

       // call large_of() with 2 arguments stored in x and y respectively

       z = larger_of(x, y);

       printf("\nThe larger value is %d.", z);

       printf("\n");

 }

 

// a callee

// a function definition, must receive 2 arguments stored (copied) in a and b respectively

// and must return a value of type int

int larger_of(int a, int b)

{

       // return a or b

       if(a > b)

           return a;

       else

           return b;

}

 

Output:

 

C/C++ function return different values

 

4.5.5    The Function Prototype

  • Must be included for each function that it uses, (required by Standards for C++ but optional for C) if not directly declare and define before main().

  • In most cases it is recommended to include a function prototype in your C program to avoid ambiguity.

  • Identical to the function header, with semicolon (;) added at the end.

  • Function prototype includes information about the function’s return type, name and parameters’ list and type.

  • The general form of the function prototype is shown below,

function_return_type    function_name(type parameter1, type parameter2,…, type parameterN)

  • The name is optional and the following is an example of function prototype.

long cube(long);

  • Function prototype provides the C/C++ compiler with the name and arguments of the functions contained in the program and must appear before the function is used or defined.  It is a model for a function that will appear later, somewhere in the program.

  • So, for the above prototype, the function is named cube, it requires a variable of the type long, and it will return a value of type long.

 

C/C++ function prototype

// function prototype code snippet example

// this example cannot be compiled or run

double   squared (double);        // function prototype

void   print_report (int);              // function prototype

 

double  squared(double number)    // function header

{                                                           // opening bracket

       return (number * number);         // function body

}                                                          // closing bracket

 

void    print_report(int report_number)

{

       if(report_number  == 1)

              printf("Printing Report 1");

       else

              printf("Not printing Report 1");

}

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

 

 

Further C and C++ reading and digging:

  1. Check the best selling C / C++ books at Amazon.com.
  2. For this Module purpose, you can check the standard libraries of these various standards of C / C++.  Explore and compare the standard functions and their variation if any in the libraries.  You can download or read online the specification at the following links. (ISO/IEC is covering ANSI and is more general):
  1. ISO/IEC 9899 (ISO/IEC 9899:1999) - C Programming languages.
  2. ISO/IEC 9945:2002 POSIX standard.
  3. ISO/IEC 14882:1998 on the programming language C++.
  4. ISO/IEC 9945:2003, The Single UNIX Specification, Version 3.
  5. Get the GNU C library information here.
  6. Read online the GNU C library here.

 

 

 

 

 

 

 

|< Let Have A Break! | Main | C & C++ Functions 2 >| Site Index | Download |


C and C++ Functions:  Part 1 | Part 2 | Part 3 | Part 4 |