Why is the value of this variable changing to garbage once inside for-loop? C

StackOverflow https://stackoverflow.com/questions/15307367

  •  18-03-2022
  •  | 
  •  

Вопрос

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

Это было полезно?

Решение

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

Другие советы

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
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top