You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中间结果与未定义行为:修改变量类型为何能解决溢出?

Why Changing Variable Types Fixes Integer Overflow in C++?

Great question—this is a super common pitfall when working with integer arithmetic in C++, so let's break it down step by step.

1. The Rule Behind Intermediate Results in C++

When you multiply two variables of type int in C++, the intermediate result of the multiplication is also an int—even if you plan to store that result in a larger type later. That means your expression n * x2 first gets computed as an int value. If that computed value exceeds the maximum limit that an int can hold, you hit integer overflow, which leads to undefined behavior (in your case, that weird incorrect output t=1107970048).

2. Range Differences Between int and long int

Here's the key: int and long int have drastically different storage capacities:

  • On most modern systems, an int is 32 bits, which can hold values from -2^31 (-2147483648) to 2^31-1 (2147483647).
  • A long int (often 64 bits on modern systems) can hold values from -2^63 to 2^63-1—that's a massively larger range, easily capable of fitting your correct result 888681381120000.

When you used int variables, the multiplication overflowed the int range, wrapping around to a garbage value. When you switched to long int, the intermediate result of n * x2 became a long int, which has enough space to hold that large number without overflowing—hence the correct output.

3. A Quick Alternative (If You Don't Want to Change Variable Types)

Just for completeness: you don't have to change the variable types to fix this. You can also force a type conversion in the expression to promote one operand to long int, which will make the whole multiplication use long int for the intermediate result:

long int t = static_cast<long int>(n) * x2;

This works because C++ will automatically promote the other operand (x2) to long int to match, avoiding the overflow entirely.


内容的提问来源于stack exchange,提问作者md zaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:27:50