This is an easy mistake for a beginner to C++ to make. Let's look at other languages, like PHP:
function add ($a, $b)
{
return $a + $b;
}
Or Lua:
function add (a, b)
return a + b
end
Or JavaScript:
function add (a, b)
{
return a + b;
}
Or VBscript:
Function add (a, b)
add = a + b
End Function
All those languages have the word "function" there to indicate that you are declaring a function.
So what does C++ look like:
int add (int a, int b)
{
return a + b;
}
So this must be an "int" right? Or what if it doesn't return a value?
void loop ()
{
}
Now it's a "void"? Kind of a weird name for a function!
Actually int
and void
in these examples are not weird names for functions. They are the return types of those functions. int add (int a, int b)
is a function that returns an int. And void loop ()
is a function that returns nothing.
The C++ compiler can deduce when it is seeing a function declaration from some clues:
- A return type (eg. int, float, long)
- A name (the function name)
- Some parentheses (for the function arguments)
Think of the word function
as being there in spirit:
int [function] add (int a, int b)
^^^^^^^^^^ <-- don't actually type this!
{
return a + b;
}
procedure
andfunction
declarations, and thought that C had very weird syntax. And before Turbo Pascal, well that's a whole other story. :)