1.4 Functions

Functions are declared and defined in the following way:

<return_type> <function_name>(<params>) {
    // do something
    return something;
}

For example:

#include <iostream>

float square(float a)
{
    return a * a;
}

int main()
{
    float x = 2.5;
    std::cout << "square of " << x << "is" << square(x) << std::endl;
}

Note that a function must be declared before it can be used. This means the following won’t work:

#include <iostream>

// float square(float);

int main()
{
    float x = 2.5;
    std::cout << "square of " << x << "is" << square(x) << std::endl;
}


float square(float a)
{
    return a * a;
}

However, by uncommenting the third line, it works. When you use a function, the compiler must know the signature, but not necessarily the definition of the function. This is why in C++ (and in C) people split their funtions into signatures which go into header files, and definitions which go into .cpp files. I’ll get back to header files later. For now we’ll be working with single-file programs without splitting declaration and definitions.