Skip to content

UB49⚓︎

Author: PeiHong Dai

Definition⚓︎

  • An expression having signed promoted type is left-shifted and either the value of the expression is negative or the result of shifting would not be representable in the promoted type (6.5.7).
  • 左移具有带符号提升类型的表达式时,表达式的值是负数或移位结果不能用提升类型表示

Description⚓︎

  • If \(E1\) has a signed type and nonnegative value, and \(E1 \times 2^{E2}\) is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined. (P85)

Code⚓︎

#include  <stdio.h>
int main(void)
{
    char src = 100;
    int shift = 29;
    printf("%d\n", src << shift);
    return 0;
}

Configurations⚓︎

OS: Microsoft Windows 11 22H2

gcc -v : gcc version 7.4.0, x86_64-w64-mingw32

compile and run commands: gcc -o UB49.exe UB49.c && ./UB49.exe
OS: Microsoft Windows 11 22H2

clang -v : clang version 6.0.0, x86_64-w64-mingw32

compile and run commands: clang -o UB49.exe UB49.c && ./UB49.exe

Behaviors⚓︎

compilation successful
output:
-2147483648
compilation successful
output:
-2147483648

Advice⚓︎

  • When shifting types (especially signed) with promotions, double check for boundary violations.

  • Table of common Promotions in C

  • Original Type Usually Promoted To
    char int
    bit-field int
    enum int
    unsigned char int
    short int
    unsigned short int
    float double
    array of anything pointer to anything