This question is a result of another SO question.
Example Code
#include <iostream>
int main()
{
unsigned long b = 35000000;
int i = 100;
int j = 30000000;
unsigned long n = ( i * j ) / b; // #1
unsigned long m = ( 100 * 30000000 ) / b; // #2
std::cout << n << std::endl;
std::cout << m << std::endl;
}
Output
85
85
Compiling this code with g++ -std=c++11 -Wall -pedantic -O0 -Wextra
gives the following warning:
9:28: warning: integer overflow in expression [-Woverflow]
Questions
-
Am I correct in thinking that
#1
and#2
invoke undefined behavior because the intermediate result100 * 30000000
does not fit into anint
? Or is the output I am seeing well-defined? -
Why do I only get a warning with
#2
?
Best Answer
Yes, it is undefined behaviour, and the result you get is usually¹ different if
unsigned long
is a 64-bit type.¹ It's UB, so there are no guarantees.