I dont want to show them a hard coded variable, what if the variable needed to be changed? using a name is better because the contents of a variable name can be changed, but I will show them your way too.
You should show them something semi-useful of each data type maybe?
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
constint add( constint &x , constint &y ) //I suggest using reference so you don't create a copy
{
return( x + y );
}
int main()
{
int x , y;
std::cout << "Please enter two values." << std::endl;
std::cin >> x >> y;
std::cout << x << " + " << y << " = " << add( x , y ) << std::endl;
}
I dont want to show them a hard coded variable, what if the variable needed to be changed?
Err.... this:
1 2 3 4 5
int returnInt()
{
int foo = 10;
return foo;
}
... is just as hardcoded as this:
1 2 3 4
int returnInt()
{
return 10;
}
And both are of equal difficulty to change later. You just change the "10" to something else.
giblit wrote:
I suggest using reference so you don't create a copy
For complex types like string, I'd agree. But passing basic data types like ints by reference instead of by value is more likely to worsen performance rather than improve it.
Copying the reference/pointer to x is just as expensive as copying x by value. Only now you also have to dereference a pointer/reference in the function to access the data which is slower.
but what if I wanted to return a random value while using the program? the user has no access to the source so what i meant was what if someone did something like this:
1 2 3 4 5 6 7 8 9
void function()
{
int number = 0;
cout << "Enter a random number" << endl;
cin >> number;
return number;
}
thats what i meant. Also i indented all of the code so it would be easier to read.
Well clearly that function is totally different and therefore needed to be rewritten regardless. And yeah since you're returning a variable value you need a variable.
But if you're just returning a fixed value you don't need to assign it to a variable first because it's fixed.
I want to show them how to do everything, I dont want any generalizing, or anything. I dont want to assume anyone knows how to do anything, thats how the people who taught me thought and i ended up paying for it in the end, i should know all of this stuff by now and tons more but i dont because people just assume you should be able to figure it out but I dont work like that so i want to make this tutorial for everyone.