int number ; // local variable defined at function scope
std::cout << "please enter a number: " ;
std::cin >> number ; // get value from user
return number ;
If I was wanting to create a function of type float which returned the calculated value from the function would this work?
float convertor ();//declaration of prototype
//function takes inputted temp in celsius and converts it to fahrenheit and returns the value
cout << "Please enter temperature in Celsius: ";
cin >> temp_celsius;
return (((temp_celsius * 9)/5) + 32);
If I were to call this function would it return the calculated value?
// prefer using double as the floating point type
// give the function and its parameters names pregnant with meaning
// the function takes as input the temperature in celsius
// and returns the equivalent temperature in fahrenheit
double to_fahrenheit( double celsius ) ;
And get the input (temperature in celsius) from the user in main() and pass it to the function.
1 2 3 4
double temp_celsius ;
std::cout << "please enter temperature in celsius: " ;
std::cin >> temp_celsius ;
constdouble temp_fahrenheit = to_fahrenheit(temp_celsius) ;
A good function is a function that does one small thing, and does it well.
This one converts from celsius to fahrenheit, it doesn't need to know how the celsius value was obtained.
I am quite new to programming and would like to get in to good habits early.
Someone told me that it is best to keep the main body as free as possible and that is why I thought of putting the variable in the function, as it was not going to be used anywhere outside of the function.
However, I take your point that by declaring the variable in the main program it makes the code easier to reuse in the future as I can export the convertor function.
Keeping the main function as free as possible doesn't mean to not put stuff in it as much as not to clutter it up and make it hard to understand. Suppose you were asked one week to write a function that added two numbers and then two weeks later asked to modify it to multiply the result with another number. You would just be cluttering up your function instead of main. Something like this is much easier read.
int add(int a, int b);
int multiply(int a, int b);
cout << "Enter a number:";
cin >> a;
cout << "Enter another number to add to the first:";
cin >> b;
first = add(a, b);
cout << a << " plus " << b << " is " << first << '\n';
cout << "Enter a number to multiply the first result by:";
cin >> x;
second = multiply(first, x);
cout << first << " times " << x << " is " << second << '\n';
int add(int a, int b)
return a + b;
int multiply(int a, int b)
return a * b;
Besides being able to reuse your first function as JLBorges said, it is easier to just modify what your asking the user in main and get all kinds of different variations. The variable list might get longer along with the cout/cin statements but that's about all.