Scope of (string) literals

前端 未结 7 1339
半阙折子戏
半阙折子戏 2020-11-27 18:13

I always try to avoid to return string literals, because I fear they aren\'t defined outside of the function. But I\'m not sure if this is the case. Let\'s take, for example

7条回答
  •  无人及你
    2020-11-27 18:55

    I give you an example so that your confusion becomes somewhat clear

    char *f()
    {
    char a[]="SUMIT";
    return a;
    }
    

    this won't work.

    but

    char *f()
    {
    char *a="SUMIT";
    return a;
    }
    

    this works.

    Reason: "SUMIT" is a literal which has a global scope. while the array which is just a sequence of characters {'S','U','M','I',"T''\0'} has a limited scope and it vanishes as soon as the program is returned.

提交回复
热议问题