23) Functions¶
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 | |
main(). Other than that, you might have used pow(), get.line(), setw(), and more. These are all built-in functions. In some of them (like pow()), you can enter values and then they do specific things. Now, you’ll be making your own functions and doing things with them.(Optional) Function Declaration/Prototyping
(Compulsory) Function Definition
(Compulsory) Function Calling
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
myFunc, and it’s being called in int main(). The output would be three lines of Hello World!.return type | name | arguments.Return Type is a Data Type. It can either be
int, float, double, bool, char, string, void. The new one among those isvoid. Return Type means that when the Function is done doing its thing, then it returns a value. Exactly how the Maths functions work. They return a value, and only one value. That’s why we writereturn 0;at the end ofint main(). If there’s no value to return, however, then you usevoid, as shown in the example above. If a function does not have a Return Type, then a Variable can’t be assigned the value of it. You can doa = pow(4, 5), but if thepow()function used thevoidReturn Type, then you wouldn’t be able to do that. You also have to make sure that the data type matches. You can’t define a function as anintand then return2.0, for example.Name means the name of the Function. In the example above, it’s called
myFunc. It follows the same naming style as regular Variables.Arguments are values given to the function from the outside. Remember how
pow()needs values? So you’d write something likepow(5, 3)to get 53 .5and3are Arguments. They’ll be talked about on the next page.
void myFunc() is the line where the Function is defined, and myFunc(); is the line where the Function is called. But if you move the Definition of the Function to be after int main(), it’ll give an error. It’s like calling a Variable before it was declared.int main(), or to do something called a Function Declaration so you can put the actual Definition anywhere you want. Function Declaration is also called Prototyping. It was the Optional thing involved with Functions.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |