C 变量的范围 [英] Scope of C variables

查看:27
本文介绍了C 变量的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
正在从功能安全且便携?
“life-time”C 中的字符串字面量

你好,我有点困惑

char *func()
 {

    return "Hello";
 }

这里的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?

推荐答案

"Hello" 是一个字符串文字,将在程序的生命周期内存在.引用C99标准的相关部分:

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 字符串文字

...然后使用多字节字符序列初始化一个静态存储持续时间的数组,并且长度刚好足以包含该序列...

...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 对象的存储期限
  • 一个对象,其标识符是用外部或内部链接声明的,或者用存储类说明符 static 具有静态存储持续时间.它的生命周期是整个程序的执行及其存储的值仅在程序之前初始化一次启动.

    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.

    函数的返回值应该是 const char* 因为尝试修改字符串文字是未定义的行为.

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

    这篇关于C 变量的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆