Question

Why is the value of n changing to garbage inside the for-loop? (I'm new to C language, I come from a C++ background)

float n = 3.0;
printf ("%f\n", n);
for (; n <= 99.0; n += 2)
    printf ("%f\n", &n);

enter image description here

Was it helpful?

Solution

You are printing the address of n (&n) inside the for-loop. Get rid of the &

OTHER TIPS

Your error is in how you're trying to print out n. You're passing the address of the n instead of the value.

You're gaining nothing by using floating point in this case. While it'll work, an int will work just as well:

int n = 3;
printf ("%d\n", n);
for (; n <= 99; n += 2)
    printf ("%d\n", n);

In C it's also more common to use < for your loop termination condition, so something like:

for ( ; n<100; n+=2)

...for the loop condition would usually be preferred.

error in your for loop condition, you forgot to add suffix f:

do like:

for (; n <= 99.0f; n += 2)
                ^

remember: unsuffixed floating-point literals are doubles, which is a more commonly used floating point type than float.

second printf error: @adrianz answers

 printf ("%f\n", &n);
                 ^  remove it
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top