Functions
We kind of figured out what a variable is: it's a place to store some data, like numbers, in memory; and we can assign the values of arithmetic expressions to variables, like we did for the amount
:
amount = price * count;
Before we go further, we'll need to introduce one more thing: a function.
A function is basically a piece of code that takes some parameters and evaluates – we say returns – a value which is a result of the function. We can write the calculation above as a function:
int calculate_amount(int price, int count) {
return price * count;
}
There's some similarity to a variable declaration: a function declaration starts with a type the function returns (int
), then its name (calculate_amount
), then parameters (price
and count
, both of type int
). Basically, this function takes two values: price
and count
, and returns the amount by multiplying them together. Now you can write
amount = calculate_amount(5, 7);
or use variables – and yes, you can declare multiple variable in one line:
int price, count, amount;
price = 5;
count = 7;
amount = calculate_amount(5, 7);
Now that we know how to write simple functions, we are very close to writing and running a real program!