Recent Changes - Search:

Coding C++

Computing

Procedural: Functions

Trail Index | Procedural | Functions

Functions in C++ may resemble closely the mathematical idea of a function: something that takes as input a series of parameters, and return a value. Or they can be, more generally, blocks of code with a well identified role.

Functions may not return a value, and in this case they are usually called subroutines.

Functions, or subroutines, also allow you to avoid duplication in your code. Duplication is bad because because it increases the probability of making mistakes, especially when the code requires changes.

/**
 * Functions
 */


// include standard input/output streams for C++
#include <iostream>

/* a very silly function */
double poly(const double x) {
    return 2*x+3*x*x;
}

/**
 * main function
 */

int main() {
    // import whole namespace - this is a sloppy usage,
    // but acceptable inside a limited scope
    using namespace std;

    { // values of polynomial at different x values
        for (double x=0;x<10;x+=.5) {
            cout<< 2*x+3*x*x <<endl;
        }
        // same poly, but with x translation, and scaling
        // ugly, hard to read, hard to change consistently
        // across a whole large program
        for (double x=0;x<10;x+=.5) {
            cout<< (2*(x+1)+3*(x+1)*(x+1))/5 <<endl;
        }
    }

    { // same thing, using a function !
        for (double x=0;x<10;x+=.5) {
            cout<< poly(x) <<endl;
        };
        for (double x=0;x<10;x+=.5) {
            cout<< poly(x+1)/5 <<endl;
        };
    }
    return 0;
}

< Flow Control Structures | Trail Index | Writing Code >

Edit - History - Print - Recent Changes - Search
Page last modified on December 09, 2022, at 05:01 pm