|< C & C++ Functions 1 | Main | C & C++ Functions 3 >| Site Index | Download |


 

 

 

MODULE 4a: MORE ON C/C++ FUNCTIONS 2

Receive nothing, return nothing-receive nothing, return something-
receive something, return something-receive something, return nothing
And they do something.  That is a function!
declare, define and use it

 

 

 

 

 

 

 

 

My Training Period: xx hours

 

This is a continuation from the previous Module. 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 should be acquired:

 

  • Able to understand parameters and arguments.

  • 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.6    Passing Arguments To A Function

  • In order function to interact with another functions or codes, the function passes arguments.

  • The called function receives the values passed to it and stores them in its parameters.

  • List them in parentheses following the function name.

  • A program example:

#include <iostream>

using namespace std;

 

// a function prototype

void  prt(int);

 

// the main function definition

int main()

{

       // declare an integer variable

       int x=12;

       // calls prt() and passes x, so main() is a caller

       prt(x);

       cout<<endl;

       return 0;

}

 

// the prt() function definition, receive an argument copied into y and return nothing

// this is a callee

void  prt(int y)

{

       // local variable…

       int p = 30;

       // value from caller

       cout<<"Value from the calling program..."<<endl;

       cout<<"x's value = "<<y<<endl;

       // local variable value

       cout<<"\nLocal variable value..."<<endl;

       cout<<"p's value = "<<p<<endl;

}

 

Sample output:

 

C/C++ function passing arguments

C/C++ function arguments and parameters

  1. Passing by value – you learn in this Module.

  2. Passing by (memory) address – you will learn in Array and Pointer Modules.

  3. Passing by reference (C++ only) – also in Array and Pointer Modules.

4.7    Macros and Inline Functions

4.7.1    Macros

C/C++ function vs macro

cout<<"\nArea = "<<area(4.0, 6.0);

#define avg(x, y) (x + y)/2.0

avg1 = avg(avg(a, b), avg(c, d))

avg4 = ((a + b)/2.0 + (c + d)/2.0) / 2.0

4.7.2    Inline Function

// calculating an area of triangle using inline function

#include <iostream>

using namespace std;

 

// an inline function, no need prototype…

inline float triangle_area(float base, float height)

{

       float area;

       area = (0.5 * base * height);

       return area;

}

 

int main()

{

       float b, h, a;

       b = 4;

       h = 6;

       a = triangle_area(b, h);

       cout<<"Area = (0.5*base*height)"<<endl;

       cout<<"where, base = 4, height = 6"<<endl;

       // compiler will substitute the inline function code.

       cout<<"\nArea =  "<<a<<endl;

       return 0;

}

 

Sample output:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

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

C/C++ function vs macros

 

4.8    Header Files and Functions

4.8.1    Standard Header File

#include <header_filename.h>

#include <iostream>

 

int main()

{ return 0; }

Header file

ANSI C/ISO/IEC?

Purpose

alloc.h

-

Declares memory-management functions (allocation, de-allocation, and so on).  Example: calloc(), malloc(), farfree().

assert.h

ANSI C

Defines the assert debugging macro.

bcd.h

C++

Declares the C++ class bcd (binary coded decimal) and the overloaded operators for bcd and bcd math functions.

bios.h

-

Declares various functions used in calling IBM®-PC ROM BIOS routines.  Example: biosequip(), bioskey(), biosprint().

checks.h

C++

Defines the class diagnostic macros.

complex.h

C++

Declares the C++ complex math functions.

conio.h

-

Declares various functions used in calling the operating system console I/O routines.  Example: getch(), gotoxy(), putch(), outport().

constrea.h

C++

Defines the conbuf and constream classes.

cstring.h

C++

Defines the string classes.

ctype.h

ANSI C

Contains information used by the character classification and character conversion macros (such as isalpha() and toascii()).  Example: isalnum(), isupper(), isspace().

date.h

C++

Defines the date class.

dir.h

-

Contains structures, macros, and functions for working with directories and path names.  Example: chdir(), getcurdir(), mkdir(), rmdir().

direct.h

-

Defines structures, macros, and functions for dealing with directories and path names.

dirent.h

-

Declares functions and structures for POSIX directory operations.  Example: closedir(), opendir(), readdir().

dos.h

-

Defines various constants and gives declarations needed for DOS and 8086-specific calls.  Example: bdos(), _chmod(), getdate(), gettime().

errno.h

ANSI C

Defines constant mnemonics for the error codes.

except.h

C++

Declares the exception-handling classes and functions.

excpt.h

-

Declares C structured exception support.

fcntl.h

-

Defines symbolic constants used in connection with the library routine open.  Example: _fmode(), _pipe().

file.h

C++

Defines the file class.

float.h

ANSI C

Contains parameters for floating-point routines.

fstream.h

C++

Declares the C++ stream classes that support file input and output.

generic.h

C++

Contains macros for generic class declarations.

io.h

-

Contains structures and declarations for low-level input/output routines.  Example: access(), create(), close(), lseek(), read(), remove().

iomanip.h

C++

Declares the C++ streams I/O manipulators and contains templates for creating parameterized manipulators.

iostream.h

C++

Declares the basic C++ streams (I/O) routines.

limits.h

ANSI C

Contains environmental parameters, information about compile-time limitations, and ranges of integral quantities.

locale.h

ANSI C

Declares functions that provide country- and language-specific information.  Example: localeconv(), setlocale().

malloc.h

-

Declares memory-management functions and variables.

math.h

ANSI C

Declares prototypes for the math functions and math error handlers.  Example: abs(), cos(), log(), pow(), sin(), tan().

mem.h

-

Declares the memory-manipulation functions. (Many of these are also defined in string.h.).  Example: memccpy(), movedata(), memset(), _fmemmove(), memchr().

memory.h

 

Contains memory-manipulation functions.

new.h

C++

Access to _new_handler, and set_new_handler.

process.h

-

Contains structures and declarations for the spawn... and exec... functions.  Example: abort(), exit(), getpid(), wait().

search.h

-

Declares functions for searching and sorting.  Example:  bsearch(), lfind(), qsort().

setjmp.h

ANSI C

Declares the functions longjmp and setjmp and defines a type jmp_buf that these functions use.  Example: longjmp(), setjmp().

share.h

-

Defines parameters used in functions that make use of file-sharing.

signal.h

ANSI C

Defines constants and declarations for use by the signal and raise functions.  Example: raise(), signal().

stdarg.h

ANSI C

Defines macros used for reading the argument list in functions declared to accept a variable number of arguments (such as vprintf, vscanf, and so on).

stddef.h

ANSI C

Defines several common data types and macros.

stdio.h

ANSI C

Defines types and macros needed for the standard I/O package defined in Kernighan and Ritchie and extended under UNIX System V. Defines the standard I/O predefined streams stdin, stdout, stdprn, and stderr and declares stream-level I/O routines.  Example: printf()/printf_s(), scanf()/scanf_s(), fgets()/fgets_s(), getchar(), fread().

stdiostr.h

C++

Declares the C++ (version 2.0) stream classes for use with stdio FILE structures. You should use iostream.h for new code.

stdlib.h

ANSI C

Declares several commonly used routines such as conversion routines and search/sort routines.  Example: system(), time(), rand(), atof(), atol(), putenv().

string.h

ANSI C

Declares several string-manipulation and memory-manipulation routines.  Example:  strcmp(), setmem(), _fstrcpy(), strlen().

strstrea.h

C++

Declares the C++ stream classes for use with byte arrays in memory.

sys\locking.h

-

Contains definitions for mode parameter of locking function.

sys\stat.h

-

Defines symbolic constants used for opening and creating files.

sys\timeb.h

-

Declares the function ftime and the structure timeb that ftime returns.

sys\types.h

-

Declares the type time_t used with time functions.

thread.h

C++

Defines the thread classes.

time.h

ANSI C

Defines a structure filled in by the time-conversion routines asctime, localtime, and gmtime, and a type used by the routines ctime, difftime, gmtime, localtime, and stime. It also provides prototypes for these routines.

typeinfo.h

C++

Declares the run-time type information classes.

utime.h

-

Declares the utime function and the utimbuf struct that it returns.

values.h

-

Defines important constants, including machine dependencies; provided for UNIX System V compatibility.

varargs.h

-

Definitions for accessing parameters in functions that accept a variable number of arguments. Provided for UNIX compatibility; you should use stdarg.h for new code.

 

Table 4.1:  A list of some standard and non standard header files

 

4.8.2    Using Predefined Functions in Header File

4.8.3    User-defined Header Files

#include "myfile.h" 

// enclosed with " ", instead of < >

// because it is located in the same folder/directory

// as the main() program instead of the standard path of

// of the include files set during the compiler installation.

 

int main()

{ return 0; }

4.8.4  Variadic Functions

4.8.4.1  The Usage

int testfunc(int, char *);

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

4.8.4.2 Definition

  1. Define the function as variadic, using an ellipsis ('...') in the argument list, and using special macros to access the variable arguments.

  2. Declare the function as variadic, using a prototype with an ellipsis ('...'), in all the files which call it.

  3. Call the function by writing the fixed arguments followed by the additional variable arguments.

4.8.4.3  The Syntax for Variable Arguments

int varfunc(const char *a, int b, ...)
{ return 0; }      

4.8.4.4  Receiving the argument Values

  1. You initialize an argument pointer variable of type va_list using va_start. The argument pointer when initialized points to the first optional argument.

  2. You access the optional arguments by successive calls to va_arg. The first call to va_arg gives you the first optional argument; the next call gives you the second, and so on. You can stop at any time if you wish to ignore any remaining optional arguments. It is perfectly all right for a function to access fewer arguments than were supplied in the call, but you will get garbage values if you try to access too many arguments.

  3. You indicate that you are finished with the argument pointer variable by calling va_end.

4.8.4.5  How Many Arguments Were Supplied

4.8.4.6  Calling Variadic Functions

4.8.4.7  Argument Access Macros

Data Type: va_list

The type va_list is used for argument pointer variables.

 

Macro: void va_start (va_list ap, last-required)

This macro initializes the argument pointer variable ap to point to the first of the optional arguments of the current function; last-required must be the last required argument to the function.

 

Macro: type va_arg (va_list ap, type)

The va_arg macro returns the value of the next optional argument, and modifies the value of ap to point to the subsequent argument. Thus, successive uses of va_arg return successive optional arguments.

The type of the value returned by va_arg is type as specified in the call.  type must be a self-promoting type (not char or short int or float) that matches the type of the actual argument

 

Macro: void va_end (va_list ap)

This ends the use of ap. After a va_end call, further va_arg calls with the same ap may not work. You should invoke va_end before returning from the function in which va_start was invoked with the same ap argument.

 

4.8.4.8  Program Example of a Variadic Function

/* variadic function */

#include <stdarg.h>

#include <stdio.h>

 

/* variadic function's prototype, count variable is the number of arguments */

int sum_up(int count,...)

{

va_list ap;

int i, sum;

/* Initialize the argument list. */

va_start (ap, count);

sum = 0;

for (i = 0; i < count; i++)

/* Get the next argument value. */

sum += va_arg (ap, int);

/* Clean up. */

va_end (ap);

return sum;

}

 

int main(void)

{

/* This call prints 6. */

printf("%d\n", sum_up(2, 2, 4));

/* This call prints 16. */

printf("%d\n", sum_up(4, 1, 3, 5, 7));

return 0;

}

 

Output:

 

C/C++ variadic function

 

C & C++ programming tutorials

 

 

 

 

 

 

 

 

 

 

 

Further C and C++ related readings:

 

  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.

 

 

 

 

 

|< C & C++ Functions 1 | Main | C & C++ Functions 3 >| Site Index | Download |


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