So here I was having all sort of difficulty with a specific C program I had to write. Every printed number was a zero. So I tried a few different things to fix the problem, to no avail. Then I wrote a little test program:
Firstly - you need at least some parens for main -
void main()
The prototype for main is usually
int main(int argc, char* argv)
but I believe there’s some leniency there. As SenorBeef pointed out you also need a semicolon after each statement, viz.
p = 1;
Also, your printf is very questionable:
&p is the address of the variable p, i.e. (on Windows) a 32-bit pointer value. To print one of those (if that’s what you really want) you need a “%p” format specifier:
printf (“p=%p”, &p);
To print out a float, it’s %f as the format specifier, then just specify the variable, not its address:
printf (“p=%f”, p);
When I do this under Microsoft Visual C++ 6.0 I get
wolfstu - please at least satisfy my curiosity as to how your original program compiled - is Dev C++ a VERY lenient compiler, or did you retype the program from memory and make a couple of typos?
wolfstu - there’s definitely a place for ampersands, but that isn’t one of them. Not to be condescending, but could you or your professor be getting confused with scanf(), which does usually use ampersands?
I cut-pasted your program into Visual C++, and got p=1.000000 as expected. Either
(1) Visual C++ is doing something non-ANSI (any standards experts out there?)
wolfstu, when working with floats, some compilers will require you to use 1.0 instead of 1. I believe the ANSI standard requires this also. Gcc is compiling it correctly without the decimal point, so I’m not sure if that’s your problem, and that is the only compiler which I have available to me right now.
Ampersands are for making pointers to variables, & means “address of” when it comes right before a variable name. For %f and %d, and so on, printf does not want a pointer, it wants the variable itself.
You may be confusing printf with scanf, as DarrenS suggested, which requires a pointer so it can write data to the variable.
For what’s it’s worth, without looking over the ANSI standard itself, gcc with the -ansi and -pedantic flags on will compile “float p = 1;” without complaint 1.0 is to be preferred for matters of clarity, 1.0f if you are really intent on being clear.