目标-C“ const”表示题 [英] Objective-C "const" question

查看:76
本文介绍了目标-C“ const”表示题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Wikipedia说 const是 ...一种特殊的变量,其值通常在程序执行期间无法更改...

Wikipedia says "const" is "...a special kind of variable whose value cannot typically be altered by the program during its execution..."

如果就是这种情况,为什么这样做:

If that is the case, why does this:

const char *words[4] = { "aardvark", "abacus", 
                             "allude", "zygote" };

    *words = "first";
    words[1] = "second";

    int wordCount = 4;

    int i;
    for (i = 0; i < wordCount; i++) {
        NSLog (@"%s is %d characters long",
               words[i], strlen(words[i]));
    }

输出为:
第一个
second
allude
zygote(显然带有长度等)

have an output of: "first" "second" "allude" "zygote" (obviously with the length etc.)

我认为 const的重点是防止变量被修改?

I thought the whole point of "const" was to prevent the variable of being modified??

推荐答案

const 适用于 char ,即字符串本身的内容,但不适用于数组。如果希望数组的内容也保持不变,则需要在每个级别上添加 const

The const only applies to the char, i.e. the content of the strings themselves, but not to the array. If you want the content of the array to be constant as well, you need to add const to every level:

char const* const words[4] = { "aardvark", "abacus", "allude", "zygote" };
//   ^      ^
//   |      This makes words[x] = "abc"; fails.
//   |
//   This makes words[x][y] = 'a'; fails

这篇关于目标-C“ const”表示题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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