Directory

Tutorial part 3, functions

Functions have been discussed a little bit so far but they are very important and need more explaining.

main

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.

Example

This may seem overwhelming, the main focus is the main function at the bottom. Just skim the code, an explanation is below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
importstd.stdio;
importstd.cstream;
importstd.conv;

// welcome message to user
voiddisplayWelcome()
{
writef("Welcome to my adding program!\n\n");
}


// ask for an integer from user and return it
intaskInt()
{
char[]line;
intnum;

writef("Enter an integer> ");

line=din.readLine();
num=std.conv.toInt(line);

returnnum;
}


voiddisplayResult(intresult)
{
writefln("The answer is %d",result);
}


// wait for user to press enter
voidwaitEnter()
{
writefln("Press enter to continue");
din.readLine();
}


intmain()
{
intanswer;// goal
intn1,n2;// operands

displayWelcome();

n1=askInt();
n2=askInt();

answer=n1+n2;//solve
displayResult(answer);

waitEnter();

return0;
}

Explanation:
  • 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:
int main()
{
 displayWelcome();
 displayResult(askInt() + askInt());
 waitEnter();
 return 0;
}
I skipped the use of the variables because the values didn't need to be saved.

Copyright © 2004-2008 Christopher E. Miller

AltStyle によって変換されたページ (->オリジナル) /