-
Function call
Hi guys, would appreciate your help since Im beginner everything in this fantastic language seems wired for me. I got the follwing codes:
1.
//The function SumTo() takes an integer and prints out the sum of all integers upto that int.
Code:
int SumTo(int nValue)
{
using namespace std;
cout<<"enter the number: ";
cin>>nValue;
int nsum=0;
for(int iii=0;iii<=nValue;iii++)
nsum+=iii;
return nsum;
}
int main()
{
using namespace std;
cout<<SumTo(int nValue)<<endl; //This way of calling the function SumTo doesnt
//work,why?
return 0;
}
2. If I on the otherhand declare my integer inside the SumTo() function then it works, as the code bellow.
Code:
int SumTo()
{
using namespace std;
cout<<"enter the number: ";
int nValue;
cin>>nValue;
int nsum=0;
for(int iii=0;iii<=nValue;iii++)
nsum+=iii;
return nsum;
}
int main()
{
using namespace std;
cout<<SumTo()<<endl;
return 0;
}
Would be thankful for some help, how can I modify the first one to work?
-
The answer to your first question is that it is simply syntactically incorrect.
As for your second question, perhaps this example would demonstrate the syntax:
Code:
#include <iostream>
int SumTo(int value)
{
int sum = 0;
for (int i = 0; i <= value; ++i)
sum += i;
return sum;
}
int main()
{
using namespace std;
cout << "enter the number: ";
int value;
cin >> value;
cout << SumTo(value) << endl;
return 0;
}
Basically, I copied over most of your code (renaming the variables and formatting). What is different is that I declared a variable in the main function, and moved over the user input/output code to the main function. The SumTo function thus deals entirely with summation.
-
Hi, Thanks alot for the help, but Im still curious: would it still work if I leave also the reading part inside the function SumTo()?
-
Yes, if you change
int SumTo(int nValue)
to
int SumTo(int& nValue)
The later basically tells the compiler to make "nValue" an alias of another variable. The problem is that all arguments gets copied, so your nValue will be local to the function. But if you make it an alias of another variable which you pass in, it will write to that variable instead.
-
Thank you very much both of you for the help!
-
Laserlight you are very helpful.
-
Still curious! Does the character & in front of int, i.e. int& makes the variable availabe everywhere in the file its defined/declared?
And what if I in the main function make following declarations:
Code:
int main()
{
...
...
int x;
int y;
int nValue;
...
....
....
return 0;
}
Will x=y=nValue? becouse of the declaration form (int& nValue) ?
Best regards!
-
No. All the & does is tell the compiler that this is real variable; it is an alias for another variable. And the variable it is an alias for is whatever you initialize it to. It behaves just the same as other variables. It can go out of scope, and will do so, just as a normal variable would and just when a normal variable would. Of course, the original variable is not destroyed when its alias is destroyed.