Reputation: 39
So, when I try to output float
variable windows says, that program crashes.
The code is:
#include <stdio.h>
int main() {
float pizza_cost = 6.28;
printf("Cost is: %f", pizza_cost);
return 0;
}
I'm building it using this a bit junky script:
cls
gcc -o ./build/output.exe main.c
cd build
output.exe
cd ..
Program outputs
But, then instantly crashes
My os is Windows7 32bit and gcc version is 12.3.0
I tried replacing %f
with %F
, swapping float
with double
, but it still crashes.
Upvotes: 3
Views: 78
Reputation: 145277
The only problem with your program is it lacks the #include <stdio.h>
preprocessor directive. Omitting the header file causes the compiler to generate code for the printf
function call that is incompatible with the actual implementation of the printf
function.
Instead of passing the arguments per the actual prototype:
int printf(const char *, ...);
the compiler infers the prototype from the argument types:
int printf(const char *, float);
The ABI for these 2 prototypes is different and potentially incompatible, causing undefined behavior. This could explain why the program crashes on your system, yet it is unlikely to be the explanation.
The compiler should produce at least a warning for this problem.
It is a pity it does not by default so you should increase the warning level (-Wall -Wextra
for gcc and clang, /W4
with Visual Studio) and make warnings errors (-Werror
).'
Here is the modified program:
#include <stdio.h>
int main(void) {
float pizza_cost = 6.28;
printf("Cost is: %f\n", pizza_cost);
return 0;
}
Update: if your program still crashes as modified, you should investigate if your system is set up correctly. You seem to be using gcc
on Windows: the compiler might be misconfigured and produce executables that are unfit to run on this system.
Update2: Another source of problems is the math library which printf
might need to perform floating point conversions. Linking your program on unix would require a -lm
command line argument, check if this works on your system.
Upvotes: 1