0

I'm wondering why example one of the code doesn't work and example two does. The only change is the repetition of 'float'. The error I get are: unused variable and uninitialized variable. Would just like an explanation so I can fully grasp why it is so. Thank you.

Example one:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    float c;

    do
    {
        printf("Hi! How much change is owed?\n");
        float c = get_float();
    }

    while (float c < 0); 
}

Example two:

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    float c;

    do
    {
        printf("Hi! How much change is owed?\n");
        c = get_float();
    }

    while (c < 0); 
}
1

It's pretty straightforward. In the second one, the code uses a single variable called c. No problems.

In the first one, by including float in the while statement, the code is redeclaring the variable c. The first c gets replaced by the second c. At that point, the while statement tries to use the new, second var c. Unfortunately, the value previously assigned no longer exist, generating the uninitialized var error. Since this second c var is not used after this, it also generates the unused var error.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

3
  • So it is best not write float c again in my specific code, and instead just use c when i want to reference it? Is it only happening because i wrote float c outside and inside the while statement? Would the same error pop up if I had them both outside, or both inside?
    – Knovolt
    Jun 7 '17 at 22:51
  • The location isn't really a factor. The problem is that you used float twice for the same var. REdeclaring a variable is a bad thing within main or the same function. A variable should only be declared once.
    – Cliff B
    Jun 7 '17 at 23:33
  • Got it, thanks for the help!
    – Knovolt
    Jun 8 '17 at 0:00

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .