Scope of C variables [duplicate]

南笙酒味 提交于 2019-11-27 07:09:38

问题


Possible Duplicate:
Is returning a string literal address from a function safe and portable?
“life-time” of string literal in C

Hello i am confused somewhat

char *func()
 {

    return "Hello";
 }

Here "Hello" is sequence/array of characters. It is a local variable and it must vanish away as soon as the function returns. Then how come we are able to get the correct value?


回答1:


The "Hello" is a string literal and will exist for the lifetime of the program. To quote the relevant sections of the C99 standard:

  • 6.4.5 String literals

...The multibyte character sequence is then used to initialize an array of static storage duration and length just sufficient to contain the sequence...

  • 6.2.4 Storage durations of objects

An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program and its stored value is initialized only once, prior to program startup.

The return value of the function should be const char* as an attempt to modify a string literal is undefined behaviour.




回答2:


It's constant and have constant address in memory.




回答3:


The function destroys the values only after returning the control.

So, By the time the return statement is encountered the "Hello" is placed to return value and then the function destroys the scope;




回答4:


take a look at this : Is returning a string literal address from a function safe and portable?

even if the string were deleted (local variable or dynmic allocation with malloc() and free()) , when you return a pointer, the value can be correct. but, this is an undifined behavior.



来源:https://stackoverflow.com/questions/12139002/scope-of-c-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!