So we are learning functions and strings. I have lots of questions, but one that is bugging me and I can't find really is what does the variables (not sure if variables is right word) in the bracket of a function do?
// example:
// taken from this site, function section //http://www.cplusplus.com/doc/tutorial/functions/
#include <iostream>
usingnamespace std;
int subtraction (int a, int b) // this part I don't understand, and sorry if its // a stupid answer
{
int r;
r=a-b;
return r;
}
int main ()
{
int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction (7,2) << '\n';
cout << "The third result is " << subtraction (x,y) << '\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n';
}
If you imagine you are the computer reading your program line by line it starts at line 13 then gets to line 16 which passes to line 6 via the function call along with the variable values as I described.
So then the computer (you in fact this time) follow the recipe from line 6 then line 7 etc until line 10.
At line 10 the return statement tells you to go back to the line where the function was called from i.e. line 16 and proceed from there. The first job is assign the r result to z and then on to line 17 etc.
So basically, it always starts at int main, and as it goes though the lines (14-21) it looks at the rest of the code to see if the other functions have returned it? like the same value? Again sorry for these questions, I'm still learning :3
void myFunc() {
int x = 5;
x = x / 2;
std::cout << x;
}
int main() {
std::cout << "5 / 2 = ";
myFunc();
return 0;
}
// === IS EXACTLY THE SAME AS === //
int main() {
std::cout << "5 / 2 = ";
{
int x = 5;
x = x / 2;
std::cout << x;
}
return 0;
}
The return statement in a function is used so that you can use the function like a variable; i.e. say a value. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int square(int x) {
return (x * x);
}
int main() {
int val = square(7);
return 0;
}
// === IS EXACTLY THE SAME AS === //
int main() {
int val = (7 * 7);
return 0;
}
Kind of, I understand it a lot better now thank you. But "int square(int x)" taken from your 2nd paragraph of code, line 1, I don't understand int x. I'm pretty sure its just like what you would do at the beginning of the program. For example int square(int x); the int x part; would be the same as,
(is it / code? first time)
[/code]
#include <iostream>
using namespace std;
int x; // samething?
int main()
{
for (x=1;x<=10;x++)
{
cout << x << endl;
}
return 0;
}
[/code]
No. Think of the parameters in functions as placeholders; i.e. you take a value and call it x. The int specifies that the placeholder value has to be an integer. As an example: