Hi all..
why the below program prints some garbage?
Code:void main() { printf("%d",3.34); }
Hi all..
why the below program prints some garbage?
Code:void main() { printf("%d",3.34); }
Because you are telling in the format string that 3.34 is an integer (which it isn't), so it's bit pattern is interpreted as if it was an integer?
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
well..
in that case even the statement
should also print some garbage right? but it doesn't...it prints 0.Code:pritnf("%d",3.00);
A double might be twice as large as an int. You might be printing the bit pattern of only half of the double that happens to be all zeros?
And exactly how is 0 not garbage (wrong answer) if it is supposed to print 3.00?
I might be wrong.
Quoted more than 1000 times (I hope).Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
>but it doesn't...it prints 0.
Undefined behavior isn't restricted in any way. It could print "I'm a little teapot" every time, which also isn't technically garbage but is equally useless.
My best code is written with the delete key.
What its printing is the first 32 bits fo the number, which in the case of a double on a little endian machine is the exponent and some bits of the mantissa. 3.34 has a non zero exponent, 3.00 has a zero exponent. Technically yoru compiler shoudl complain about type conversion, which it probably is unless you turned warnigns off. Otherwise, I would say its a nonstandard implimentation of printf() since it should do the conversion itself anyway. The simple solution is to either provide the data in a variable, which will cause type conversion, or use the correct constant type.
%f is floating point as is %gCode:printf("%.2f\n",3.34)
You need to use the right type per data value. And main() returns an int.
Double Helix STL
Read Salem's icon. void main() is allowed on many compilers, but it's not standard, so it shouldn't be used: http://faq.cprogramming.com/cgi-bin/...&id=1043284376
void main() also doesn't stop the calling environment from receiving an int from main(), even if it's an arbitrary number. The only places I believe alternative versions of main() are allowed by the standards are in environments where the program does not return, however, void main() has never been part of any official C or C++ standard.
>It breaks convention, but its not 'wrong'.
That depends on your compiler. If you're writing freestanding code, you can do what you want. If you're writing hosted code and the compiler doesn't support an extension that allows void main, the behavior is undefined. Otherwise it's implementation defined.
The short answer is that int main is always correct and well defined, while void main is not.
My best code is written with the delete key.