Tutorial part 3, functions
Functions have been discussed a little bit so far but they are very important and need more explaining.
The only function we've created thus far is main. Main is a special case function because it is where the program begins.
It is sometimes referred to as the main driver function, as it is used to call other functions, and should not become cluttered with code.
This may seem overwhelming, the main focus is the main function at the bottom.
Just skim the code, an explanation is below.
// welcome message to user
writef("Welcome to my adding program!\n\n");
// ask for an integer from user and return it
writef("Enter an integer> ");
line = din.readLine();
num = std.conv.toInt(line);
void displayResult(int result)
writefln("The answer is %d", result);
// wait for user to press enter
writefln("Press enter to continue");
int answer; // goal
int n1, n2; // operands
n1 = askInt();
n2 = askInt();
answer = n1 + n2; //solve
Line 41 is where the main function starts. In there, the first 2 lines declare variables we'll be needing, an answer and 2 operands (since this is an adder).
Next, our function named displayWelcome is called. The operands (n1 and n2) then get assigned values from our askInt function.
Now the numbers are added together and assigned to answer, and finally we display the answer using our function displayResult.
The function displayResult is slightly different from the others, it takes a parameter to display.
When it's called, we pass our variable answer to it by putting it in the parameter list (parentheses).
We know this parameter's data type is int by looking at the function header (on line 27).
Inside the function displayResult, the parameter is a local variable with the value passed to it (value of answer, from main).
The main function could have been simplified, I decided to show everything step by step.
Here is a simplified version:
displayResult(askInt() + askInt());
I skipped the use of the variables because the values didn't need to be saved.