Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

c - Why does assignment persist outside of scope but declaration does not

I was wondering if someone could explain why the following behavior occurs in C. In the following I declare a variable outside the scope and then within an inner scope (the if...else) the assignment is done, and then the assignment persists past that inner scope.

int main(int argc, char *argv[])
{
    char *str;
    if (argc == 2) {
        str = "Two";
    }
    else {
        str = "Not two";
    }
    my_print(str);
}

Not two

But for a declaration with initialization, it does not live beyond the scope.

int main(int argc, char *argv[])
{
    if (argc == 2) {
        char* str = "Two";
    }
    else {
        char* str = "Not two";
    }
    my_print(str);
}

ix.c: In function ‘main’:
ix.c:15:9: error: expected expression before ‘char’
char* str = "Not two";
.........^~~~ ix.c:16:14: error: ‘str’ undeclared (first use in this function)
my_print(str);
...............^~~

Could someone explain what that's the case? For example, why wouldn't both of the above produce the same output?

question from:https://stackoverflow.com/questions/65928338/why-does-assignment-persist-outside-of-scope-but-declaration-does-not

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your second example it's not just a "declaration with initialization": you are declaring and initialising inside the inner scope of the if branch and the else branch.


int main(int argc, char *argv[])
{
    // SCOPE A
    if (argc == 2) {
        // SCOPE B
        char* str = "Two";
    }
    else {
        // SCOPE C
        char* str = "Not two";
    }
    my_print(str);
}

So you have three different scopes. You are trying to use a variable that does not exist in the scope you are using it. To have a code that does not raise a compile-time error you should use this following code:


int main(int argc, char *argv[])
{
    // SCOPE A
    if (argc == 2) {
        // SCOPE B
        char* str = "Two";
        my_print(str);
    }
    else {
        // SCOPE C
        char* str = "Not two";
        my_print(str);
    }
}

As mentioned: "The variable is local to the scope where it's declared"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...