user11954200
user11954200

Reputation:

Why doesn't size_t complain if I keep re-declaring it?

How am I allowed to do the following in C?

char * string;
size_t string_len;
unsigned int idx;

for (idx=0; (string=src[idx]) != NULL; idx++) {
    size_t string_len = strlen(string);
    if (!(dest[idx] = malloc(string_len + 1))) {
        perror("Failed to copy string value");
        exit (EXIT_FAILURE);
    }
    dest[idx] = string;
}

Shouldn't re-declaring the size_t on line 6 raise an error, similar to if I were to redeclare int idx?

Upvotes: 0

Views: 53

Answers (1)

dbush
dbush

Reputation: 223872

When you define a variable with a given name in two different scopes, you're actually defining two separate variables with the same name, and the the one in the inner scope masks the one in the outer scope. This is perfectly legal.

You will get an error however if you attempt to define two variables with the same name in the same scope other than file scope. At file scope you may have multiple declarations but only one definition, i.e. only one of those may initialize the variable.

Upvotes: 2

Related Questions