Many functions return a value when they complete execution. You know what type of data a function will return by the type that precedes the function name. (If a function doesn’t return anything, its return type is void.)
Create a new C Command Line Tool named Degrees. In main.c, add a function before main() that converts a temperature from Celsius to Fahrenheit. Then update main() to call the new function.
#include <stdio.h> float fahrenheitFromCelsius(float cel) { float fahr = cel * 1.8 + 32.0; printf("%f Celsius is %f Fahrenheitn", cel, fahr); return fahr; } int main(int argc, const char * argv[]) { float freezeInC = 0; float freezeInF = fahrenheitFromCelsius(freezeInC); printf("Water freezes at %f degrees Fahrenheitn", freezeInF); return 0; }
See how we took the return value of fahrenheitFromCelsius() and assigned it to the freezeInF variable of type float? Pretty slick, huh?
The execution of a function stops when it returns. For example, imagine that you had this function:
float average(float a, float b) { return (a + b)/2.0; printf("The mean justifies the endn"); }
If you called this function, the printf() call would never get executed.
A natural question, then, is “Why do we always return 0 from main()?” When you return 0 to the system, you are saying “Everything went OK.” If you are terminating the program because something has gone wrong, you’ll return 1.
This may seem contradictory to how 0 and 1 work in if statements; because 1 is true and 0 is false, it’s natural to think of 1 as success and 0 as failure. So think of main() as returning an error report. In that case, 0 is good news! Success is a lack of errors.
To make this clearer, some programmers use the constants EXIT_SUCCESS and EXIT_FAILURE, which are just aliases for 0 and 1 respectively. These constants are defined in the header file stdlib.h:
#include <stdio.h> #include <stdlib.h> float fahrenheitFromCelsius(float cel) { float fahr = cel * 1.8 + 32.0; printf("%f Celsius is %f Fahrenheitn", cel, fahr); return fahr; } int main(int argc, const char * argv[]) { float freezeInC = 0; float freezeInF = fahrenheitFromCelsius(freezeInC); printf("Water freezes at %f degrees Fahrenheitn", freezeInF); return EXIT_SUCCESS; }
In this book, we will generally use 0 instead of EXIT_SUCCESS.