Subroutine - C and C++ Examples

C and C++ Examples

In the C and C++ programming languages, subprograms are termed functions (or member functions when associated with a class). These languages use the special keyword void to indicate that a function takes no parameters (especially in C) and/or does not return any value. Note that C/C++ functions can have side-effects, including modifying any variables which addresses are passed as parameters (i.e. passed by reference). Examples:

void function1(void) { /* some code */ }

The function does not return a value and has to be called as a stand-alone function, e.g., function1;

int function2(void) { return 5; }

This function returns a result (the number 5), and the call can be part of an expression, e.g., x + function2

char function3(int number) { char selection = {'S','M','T','W','T','F','S'}; return selection; }

This function converts a number between 0 to 6 into the initial letter of the corresponding day of the week, namely 0 to 'S', 1 to 'M', ..., 6 to 'S'. The result of calling it might be assigned to a variable, e.g., num_day = function3(number);.

void function4(int *pointer_to_var) { (*pointer_to_var)++; }

This function does not return a value but modifies the variable which address is passed as the parameter; it would be called with "function4(&variable_to_increment);".

Read more about this topic:  Subroutine

Famous quotes containing the word examples:

    Histories are more full of examples of the fidelity of dogs than of friends.
    Alexander Pope (1688–1744)