如何使价值在当地保持不变?

How to make value constant locally?

我的意思可以通过这个例子来说明:

char* func(const char* str1, const char* str2) {
    if (str2 != NULL) {
    ... (create some value depending on str1 and return it)
    ... (and be sure that str1 and str2 aren't change)
    }
    else
        return str1;
}

它工作正常,但我收到“警告 C4090 'return':不同的 'const' 限定符”。

我能否以某种方式使字符串在函数内部为只读,但在外部(当 return 时)可在没有警告的情况下进行修改?

您可以安全地将 const 添加到一个类型(由指针引用),但不能(安全地)删除它。所以

char *func(char *unmodified1, char *unmodified2) {
    const char *str1 = unmodified1;
    const char *str2 = unmodified2;
    // use str1 and str2
    return unmodified1;
}

如果您 100% 确定在所有情况下移除 constness 都是安全的,您可以将其丢弃

char *func(const char* str1, const char* str2) {
    if (str2 != NULL) {
    ... (create some value depending on str1 and return it)
    ... (and be sure that str1 and str2 aren't change)
    }
    else
        return (char*)str1;       // possible unsafe removal of const
}