Skip to content

Ub54⚓︎

Author: Kai Xu

Definition⚓︎

An arithmetic constant expression does not have arithmetic type; has operands that are not integer constants, floating constants, enumeration constants, character constants, predefined constants, sizeof expressions whose results are integer constants, or alignof expressions; or contains casts (outside operands to sizeof or alignof operators) other than conversions of arithmetic types to arithmetic types (6.6).

Description⚓︎

原文:An arithmetic constant expression shall have arithmetic type and shall only have operands that are integer constants, floating constants, named or compound literal constants of arithmetic type, character constants, sizeof expressions whose results are integer constants, and alignof expressions. Cast operators in an arithmetic constant expression shall only convert arithmetic types to arithmetic types, except as part of an operand to the typeof operators, sizeof operator, or alignof operator(6.6.10)

arithmetic types: Integer and floating types are collectively called arithmetic types(6.2.3.23)

Similar in meaning to UB52, but expanding in scope.

与UB52意义相似,只是扩大了适用范围。

Code⚓︎

UB54.c
int main() {
    int *p;
    1 + p + 1.5 + sizeof p;
    return 0;
}

Configurations⚓︎

OS: Microsoft Windows 10 22H2

gcc -v: gcc version 8.1.0 x86_64-w64-mingw32

compile and run commands: gcc -o UB54.exe UB54.c && UB54.exe

OS: arm64-apple-darwin20.6.0

clang -v: Apple clang version 13.0.0 (clang-1300.0.29.30)

compile and run commands: clang -o UB54.out UB54.c && ./UB54.out

Behaviors⚓︎

error: invalid operands to binary + (have 'int *' and 'double') 1 + p + 1.5 + sizeof p;

error: invalid operands to binary expression ('int *' and 'double') 1 + p + 1.5 + sizeof p;

Advice⚓︎

正常变成中没有必要进行UB54的操作。