☰
  • 首页
  • 规则分类
  • 项目介绍
search
•••

不应存在 magic string

11.14 ID_literal_magicString
目录 › next › previous

直接出现在代码中的字面常量字符串称为 magic string,不利于阅读和维护,应改用具有适当名称的常量。

示例:

void foo(const string& url)
{
    if (url == "https://foo.net") {  // Non-compliant
        bar("https://foo.net");      // Non-compliant
    }
}

当这种常量字符串散落在代码的各个角落时,不便于统一管理,造成维护上的困难。

应改为:

const char myUrl[] = "https://foo.net";  // Compliant

void foo(const string& url)
{
    if (url == myUrl) {  // Compliant
        bar(myUrl);      // Compliant
    }
}

常量初始化表达式中的常量字符串可不受本规则约束。

相关

ID_literal_magicNumber

参考

CWE-1106 C++ Core Guidelines ES.45
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.