cundeclared-identifier

What exactly qualifies as a declaration of an identifier?


I am trying to construct some code such that it takes a user's input, runs one loop, takes the end value of that loop, and then runs that value through a second loop (I am also adding to a counter each time a loop runs and printfing it at the end), this was my attempt at coding this:

{
    float input = get_float("%s", "Input: ");
    float w = input * 100;
    {
    int c = 0;
    for (int q = w; q > 24; q = q - 25)
        {
        c++;
        }
    for (int d = q; d > 9; d = d - 10)
        {
        c++;
        }
    printf("%i", c);
    }
}

The error I receive is error: use of undeclared identifier 'q'. I thought that, since it was used earlier in the code, it wouldn't be a problem to identify it later on, though obviously that's not true. Any advice on either now to properly declare 'q' would be appreciated- or perhaps my entire approach is simply misguided?


Solution

  • When you declare q in the first loop it exists only inside this one loop as a local variable

    Declaring the variable outside the for scope will leave it accessible on the second loop

    {
        float input = get_float("%s", "Input: ");
        float w = input * 100;
        {
        int c = 0;
        int q;
        for (q = w; q > 24; q = q - 25)
            {
            c++;
            }
        for (int d = q; d > 9; d = d - 10)
            {
            c++;
            }
        printf("%i", c);
        }
    }```