C变量的作用域 [英] Scope of C variables

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

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/2371668/is-returning-a-string-literal-address-from-a-function-safe-and-portable\">Is函数会返回一个字符串地址的安全和便携式?结果
  <一href=\"http://stackoverflow.com/questions/9970295/life-time-of-string-literal-in-c\">“life-time”用C 字符串的

你好,我是有点困惑

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?

推荐答案

你好是一个字符串文字,将存在于程序的生命周期。引述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贮存持续时间

其标识符被声明与外部或内部连接,或者与一个对象
  存储类说明静态拥有的静态存储持续时间即可。其寿命是整个
  方案及其存储值的执行被初始化仅仅一次,前程序
  启动。

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天全站免登陆