Chapter 2: Functions, Scopes, Namespaces, and Headers

Functions are the building blocks of a C/C++ program. The elements of a program, including functions, exist within one or more scopes. In C++, there is a special scope called a namespace. The prototypes for all standard functions are declared within various headers. These topics are examined here.

Functions

At the heart of a C/C++ program is the function. It is the place in which all program activity occurs. The general form of a function is

ret-type function_name (parameter list)
{  
  body of function
}

The type of data returned by a function is specified by ret-type. The parameter list is a comma-separated list of variables that will receive any arguments passed to the function. For example, the following function has two integer parameters called i and j and a double parameter called count:

void f(int i, int j, double count) { ...

Notice that you must declare each parameter separately.

In C89, if a function’s return type is not explicitly specified, it defaults to int. C++ and C99 do not support “default-to-int,” although most compilers will still allow it.

Functions terminate and return automatically to the calling procedure when the last brace is encountered. You may force a return prior to that by using the return statement.

All functions, except those declared as void, return a value. The type of the return value must match the type declaration of the function. Values are returned via the return statement.

In C++, it is possible to create generic functions using the keyword template. (See template in Chapter 5.)




C(s)C++ Programmer's Reference
C Programming on the IBM PC (C Programmers Reference Guide Series)
ISBN: 0673462897
EAN: 2147483647
Year: 2002
Pages: 539

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net