Cpp functions
Functions
Basics
Functions in C++ must be declared like variables. If they return a value, the type of value must be specified first. If they do not return a value, list the function type as void.
Similar to mel's procedures, you can declare variables in the function declaration as arguments. For instance, if you had a function to multiply two numbers (int num1, int num2)
// function without return value void myOtherFunction() { cout << "Hi there!"; } // function with return value int myFunction(int x, int y){ return x; } // function with default values // (y/z are both optional args now) // int myfunction(int x, int y=5, int z=10){ return x; } // c++ does not have named parameters, the common // approach for calling functions instead is work as follows window = make_window( 10, // xPosition 20, // yPosition 100, // width 50 // height );https://marcoarena.wordpress.com/2014/12/16/bring-named-parameters-in-modern-cpp/
reference args
Reference args allow you to modify arguments within a function without needing to reassign them as a return value. This can actually work out to be 'more efficient' since the values do not need to be copied/recreated inside the function at a different memory addr.
void plus_one( int &a, int &b ) { a +=1; b +=1; } int a = 5; int b = 10; plus_one(a, b) cout << "a=" << a << endl; // prints 6 cout << "b=" << b << endl; // print 11int main()
Every cpp program has the function definition
main
. never return a value from this function, this will automatically return 0 on successful run, or 1 on failure. To cpp, the main function is like python'sif __name__ == '__main__':
.int main() { }functions as args
In order to use a function as an argument in cpp, you must use a pointer to the argument.
int myfunction( int number, int number2 ){ ... } // define function void *(*myfunction)( int, int ); // stores pointer to myfunction with arg int