简体   繁体   中英

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 ?

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 , ie only one of those may initialize the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM