tartarus's bolg tartarus's bolg
  • Linux and Unix Guide
  • CMake
  • gcc
  • gdb
  • bash
  • GNU Make
  • DDCA-ETH
  • CS106L
  • CS144
  • NJU PA
  • NJU OS(jyy)
  • C
  • C++
  • Python
  • reveal-md
  • LaTex
  • Paper Reading
  • TBD
  • Linux and Unix Guide
  • CMake
  • gcc
  • gdb
  • bash
  • GNU Make
  • DDCA-ETH
  • CS106L
  • CS144
  • NJU PA
  • NJU OS(jyy)
  • C
  • C++
  • Python
  • reveal-md
  • LaTex
  • Paper Reading
  • TBD
  • c

    • Introduction
    • Representing and Manipulating Information
      • 为什么无符号数不会产生溢出?有符号数会产生溢出?
    • C Programming Tips and Tricks
    • Macro
  • cpp

  • Programming_Knowledge
  • c
tartarus
2023-06-20
目录

Representing and Manipulating Information

# 为什么无符号数不会产生溢出?有符号数会产生溢出?

在 C 语言标准的 §6.2.5/9 有这么一句话:

A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.

§3.4.3/1 有这么一句话:

An example of undefined behavior is the behavior on integer overflow.

这说明无符号数不会产生溢出,有符号数会产生溢出,并且溢出会产生 undefined behavior。

这是因为无符号数只有一种编码形式,所以无符号数的运算结果如果无法被无符号数范围表示,那么就进行取模操作,而有符号数可以有很多中编码形式,不同编码形式对于无法表示的数据可能会产生不同的结果,所以说无符号数不会溢出,有符号数会产生溢出。

笔记

  • 溢出是未定义的行为
  • 如果无符号数的运算结果无法被无符号数的范围所表示不是溢出!

C99 $6.2.6.1:3:

Values stored in unsigned bit-fields and objects of type unsigned char shall be represented using a pure binary notation.

C99 $6.2.6.2:2:

If the sign bit is one, the value shall be modified in one of the following ways:
— the corresponding value with sign bit 0 is negated (sign and magnitude);
— the sign bit has the value −(2N) (two’s complement);
— the sign bit has the value −(2N − 1) (one’s complement).

参考资料:

  • CSAPP 2.2.3 Two's-Complement Encodings:

The C standards do not require signed integers to be represented in two's-complement form, but nearly all machines do so.

  • Why is unsigned integer overflow defined behavior but signed integer overflow isn't? (opens new window)
上次更新: 12/27/2023, 8:55:47 AM
Introduction
C Programming Tips and Tricks

← Introduction C Programming Tips and Tricks→

Theme by Vdoing | Copyright © 2023-2023 tartarus | CC BY-NC-SA 4.0
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式