检查溢出

基本类型 / 数字 / 整型

# No byte type: no wrap to 44
b1 <- 200L
b2 <- 100L
b3 <- b1 + b2
# b3 = 300

# The 32-bit limit of integer
max_int <- .Machine$integer.max
# max_int = 2147483647

# Doubles go further, no overflow
a <- max_int + 1
# a = 2147483648

# Wrap on purpose: keep 8 bits
wrapped <- b3 %% 256L
# wrapped = 44

# Fixed width: check the range yourself
fits_byte <- b3 >= 0L && b3 <= 255L
# fits_byte = FALSE

# Integer overflow: NA, no wrap
overflow <- suppressWarnings(max_int + 1L)
# overflow = NA

cat("b3 =", b3, "\n")
cat("max_int =", max_int, "\n")
cat("a =", a, "\n")
cat("wrapped =", wrapped, "\n")
cat("fits_byte =", fits_byte, "\n")
cat("overflow =", overflow, "\n")

# The NA comes with a warning
msg <- tryCatch(max_int + 1L,
                warning = conditionMessage)
cat("msg =", msg, "\n")
# msg = NAs produced by integer overflow