Why Do These Both Work?


I am in the “Return” section of Chapter 5. I just completed the “Degrees” exercise. I made a mistake in copying the code from the book to my computer. My code looked like this: [code]#include <stdio.h>

float fahrenheitFromCelsius(float cel)
float fahr = cel * 1.8 + 32.0;
printf("%f Celsius is %f Fahrenheit\n");
return fahr;

int main(int argc, const char * argv[])
float freezeInC = 0;
float freezeInF = fahrenheitFromCelsius(freezeInC);
printf(“Water freezes at %f degrees Fahrenheit\n”, freezeInF);
return 0;


I then realized that I forgot to add “, cel, fahr” after “printf(”%f Celsius is %f Fahrenheit\n""

Both builds logged nearly identical output.

With the mistake:
“0.000000 Celsius is 32.000008 Fahrenheit
Water freezes at 32.000000 degrees Fahrenheit”

Without the mistake:
"0.000000 Celsius is 32.000000 Fahrenheit
Water freezes at 32.000000 degrees Fahrenheit

I was hoping someone could explain to me why the program still works and returns (nearly) the correct output even though I did not tell the program what variables to plug into my function. With the mistake, it seems like the Log Navigator would read, "32.00000 Celsius is 32.00000 Fahrenheit.

Thanks in advance.



[quote]float fahrenheitFromCelsius(float cel) { float fahr = cel * 1.8 + 32.0; printf ("%f Celsius is %f Fahrenheit\n"); return fahr; }[/quote]
Xcode should have emitted a warning about the printf statement above, a warning to the effect that more conversions than data arguments are specified.

Because the two arguments required by the conversion specifiers are missing, the above printf statement will only produce random output. For example, on my machine it produced the following:

0.000000 Celsius is 21102231349613472150829242254701157374387244482066435261111591294913704619932121091510419672419338975925112476105291998802431406462277011104012177179132465095546294520751623359127124356389224958458273108367606022144.000000 Fahrenheit


Thank you for your reply. I did receive the warning message, which is how I knew I had made the mistake. It just seemed strange that I got the correct output in spite of my error. Sounds like it may have been a coincidence.