1

In the following code, why must int nInteger be declared inside int readNumber()'s body, but int nAnswer must be declared inside the () portion of void writeAnswer()? Declaring int nInteger inside the () or declaring int nAnswer inside the function body causes the IDE to complain about too few arguments for said function. Why does this happen?

I'm using Code::Blocks and the included MinGW on a Windows 7.

#include <iostream>

int readNumber()
{
    using namespace std;
    cout << "Please enter an integer: ";
    int nInteger;
    cin >> nInteger;
    return nInteger;
}

void writeAnswer(int nAnswer)
{
    using namespace std;
    cout << "The sum is: " << nAnswer << endl;
}

int main()
{

    int x;
    int y;
    x = readNumber();
    y = readNumber();

    writeAnswer(x+y);

    return 0;
}
Flip
  • 45
  • 3

1 Answers1

0

So basicly the int readNumber() function does not require any argument to be passed. You declare a local variable so the function knows where to assign the value you type in. You declare variable int nInteger and then in the very next line you assign a value to it by calling cin >> nInteger. If there was no variable declared then your program wouldn't know where to store the value that you type in.

You can think of it as of a basket for apples. You have one basket but no apples in it, then someone gives you 2 apples that you put into the basket. In the end the return statement work like you give the basket to someone else.

Function void writeAnswer on the other hand requires an argument to be passed. As you can see there in local variable declared. What it does is to simply display "The sum is: PASSED_ARGUMENT". So basicly if you call your writeAnswer function with number 6 like writeAnswer(6) it will write "The sum is: 6".

Dashovsky
  • 137
  • 9
  • Thank you, @Dashovsky. To be honest, I'm still confused about why I must declare a variable in the function body of an `int` type function and inside the () of a `vois` type function. But now I have an ideia of what I should study further. Again, thank you for answering! – Flip Apr 15 '15 at 12:47