I am doing a Udemy C course and some doubts have arisen regarding the functions in C. One of the exercises it's about temperature conversion (celsius, F and K) using functions and when my first thought was that:
void CF(){
float temp1, temp2;
printf("Escribe que temperatura quieres convertir a Fahrenheit: ");
scanf("%f", &temp1);
temp2 = (temp1 * 1.8) + 32;
printf("La temperatura en Fahrenheit es: %f", temp2);
}
But the solved exercise uses:
float fahrenheit(float C){
float F=0;
F = (9*C)/5 + 32;
return F;
}
And entering data through "int main" program while I introduce through the function.
My questions are: - It's better to introduce data through int main code or the function? - Why he uses "Float" function and I use "void" function and works fine in both cases?
Anyway, my code works, but I want to know what is better and why.
Thanks in advance and forgive me for my english.
The purpose of a function is to encapsulate a frequently used calculation. If you code it as returning a value, then you can call it whenever you want inside a bigger program, regardless of whether you want to print out the result or not. Thus the second function is more reusable.
While there is nothing wrong with the way you wrote the function, it assumes that you sit by a keyboard to enter a value, and that you will just want to look at the conversion result.
Now imagine you program a tool which takes a list of temperatures in Celsius (from a spreadsheet), and wants to convert them all into Fahrenheit. Your function wouldn't work here, but the second version can be used with a wrapper around it to read the Celsius value from the spreadsheet, call the function, and then put the converted value somewhere else.
In general it's a good design principle to keep the functionality of a function to a minimum, so that it can be used in more different circumstances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With