0

I am getting error messages compiling this code though it seems right. What did I do wrong since i'm just following examples. I am following the examples of using the atoi function but am still getting messages:

error: declaration shadows a local variable [-Werror,-Wshadow] int k = atoi(argv[1]); ^

caesar.c:12:16: note: previous declaration is here string k = argv[1]; ^

caesar.c:13:13: error: redefinition of 'k' with a different type: 'int' vs 'string' (aka 'char *') int k = atoi(argv[1]); ^

caesar.c:12:16: note: previous definition is here string k = argv[1]; ^

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

int main(int argc, string argv[])
{
if (argc != 2)
{
    printf("Error\n");
    return 1;

    string k = argv[1];
    int k = atoi(argv[1]);
}

}

2 Answers 2

0

I think I see a couple of things to change to make this work. First, your errors are appearing because you are using k to do two different things as different variable types, string and int. To generate the key, (which I'm guessing is what you are trying to do with atoi), you can just remove the line string k = argv[1] as it is unnecessary.

Also, the way you have this written, it looks like the atoi conversion is inside of your error block, so it will not run unless it is not supposed to at all... Put it outside of that if statement block if(argc !=2) if you want it to run.

0

string k declares a variable of name k and type char* (which string is an alias for).

int k declares another variable of name k and type int.

You cannot use two variables of same name within the same scope. How would the compiler know which one you mean? It would use only one, probably the last declared. Pick different names instead.

This applies to any case where you could reach two variables of the same name, for example a local and a global variable. The variable next to the code (going from current scope outwards) will be the only one accessible, so in case of local vs. global, the local one wins. When someone (maybe you of next week) reads the code, they might miss this detail, and mistake one for the other. That's why shadowing causes warnings, or with -Werror errors.

BTW, I assume your first } was meant to be placed after the return 1;.

You must log in to answer this question.

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