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

不应使用多字符常量

11.15 ID_literal_multicharacter
目录 › next › previous

“多字符常量(multi-character literal)”指单引号之间有多个字符或非基本字符的常量,如:

'abc'  // has type int and implementation-defined value
'中'   // has type int and implementation-defined value
L'文'  // has type wchar_t and implementation-defined value

这种常量的值是由实现定义的,而且在形式上与字符或字符串常量非常相似,易被误用,故建议禁用。

示例:

void foo(int x) {
    if (x == 'tcp') {  // Non-compliant
        ....
    }
    else if (x == 'udp') {  // Non-compliant
        ....
    }
}

例中 'tcp'、'udp' 为多字符常量,在 C 代码中应改用 enum,在 C++ 代码中应改用 enum class 实现:

enum class PROT { tcp, udp };

void foo(PROT x) {
    if (x == PROT::tcp) {  // Compliant
        ....
    }
    else if (x == PROT::udp) {  // Compliant
        ....
    }
}

相关

ID_literal_suspiciousChar

依据

ISO/IEC 9899:1999 6.4.4.4(10)-implementation ISO/IEC 9899:2011 6.4.4.4(10)-implementation ISO/IEC 14882:2011 2.13.2(1)-implementation ISO/IEC 14882:2011 2.14.3(1)-implementation ISO/IEC 14882:2017 5.13.3(2)-implementation
Copyright©2024 360 Security Technology Inc., Licensed under the Apache-2.0 license.