0

I've been working on my greedy with modulo for a while now and I'm not sure what I'm doing wrong.(For the moment I'm focusing on the part where I use integers to count the number of coins, skipping the part where I need to get the correct input in form of float etc.) But the compiler continues giving me the error "greedy.c:16:13: error: declaration shadows a local variable [-Werror,-Wshadow] int nc1 = s / 25;" What am I doing wrong? (I've included all libraries)

int main(void)
{
    int s = get_int();

    int nc1;
    int nc2;
    int nc3;
    int nc4;

    if ( s >= 25 )
    {
        int nc1 = s / 25;
        int r = s % 25;
        s = r;
    }

    if (s >= 10)
      {
        int nc2 = s / 10;
        int r = s % 10;
         s = r;
      }

    if (s >=5)
      {
        int nc3 = s / 5;
        int r = s % 5;
        s = r;
      }

    else (s >= 1)
      {
        int nc4 = s;
      }

    int nc = nc1 + nc2 + nc3 + s;
}

1 Answer 1

1

You're creating multiple shadow variables in the code. A shadow variable is a new var with the same name as one that has been created earlier, but the new var is created in a place where it will have smaller scope. The shadow var will mask the original var that has greater scope. This would normally generate a warning, but the IDE treats a warning as an error.

A visual example will demonstrate this better. This demonstrates shadow vars with foo and demonstrates scope with bar (see discussion that follows).

int main()
{
    int foo;   //this is the original var. It has scope throughout main

    {
        int foo;  // this is the shadow var. It has scope only inside the
                  // curly braces immediately surrounding it.
                  // it also hides the original foo

        int bar;  // bar created here
        {
             // bar exists here.
        }
        //  bar still exists
    }

    // here, the shadow foo no longer exists and the original is again available

    // bar is out of scope and no longer exists
} 

To fix this, stop "redeclaring" vars. In other words, only write the "int" the first time. Once a var is declared, you don't need to have the var type before the var name. Also, keep in mind the scope of the variable. Simply put, a var only exists between the curly braces where it is created. (If there are nested curly braces, vars exist going into child pairs of braces, but not outside the parent braces where the var is created. See var bar above.)

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

You must log in to answer this question.

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