Denis Kulygin
Denis Kulygin

Reputation: 11

C++ int variable value

#include <iostream>
using namespace std;
int main()
{
  int intVar =1500000000;
  intVar = (intVar *10)/10;
  cout << "Value intVar equal "<<intVar <<endl;

  intVar =1500000000;
  intVar = (static_cast<double>(intVar)*10)/10;
  cout << "Value intVar equal " <<intVar<<endl;

  return 0;
}

In this example, the first answer must be incorrect (211509811) due limit of variable type int, but it isn`t. What is wrong?

Upvotes: 0

Views: 417

Answers (4)

vdavid
vdavid

Reputation: 2584

In the first case you are multiplying by 10 and dividing by 10 on the same line with nothing that can break the compiler optimizations (no function calls, variable assignments, etc.). So any decent compiler will neither multiply nor divide, the same value will be stored, and I guess that is what happened to you.

But if you break that optimization by, say, making the operation in successive calls, it may give the value you seek, e.g.:

intVar =1500000000;
intVar*=10;
intVar/=10;
cout << "Value intVar equal "<<intVar <<endl;

Possible output:

Value intVar equal 211509811

Example

But note that, in both cases, you are opening the door of Undefined Behavior. If I were you, I would not rely on the compiler optimizations or any lack thereof, especially if you work with different compilers and/or different platforms.

Upvotes: 2

Lutz Kadoch
Lutz Kadoch

Reputation: 1

You save 1,500,000,000 in an (signed)int which can hold 2,147,483,647 so you are still within the limits of an singed int. Your operation below that will be erased by the optimizer.

Upvotes: -1

gsamaras
gsamaras

Reputation: 73444

Your example invokes Undefined Behavior (UB), since signed integer overflow occurs.

When UB is invoked you cannot predict with certainty what will happen. That's what happens, thus your prediction is inaccurate. And if you change your prediction completely, since UB is invoked, it will still be inaccurate.

Upvotes: 1

eerorika
eerorika

Reputation: 238461

In this example, the first answer must be incorrect (211509811) due limit of variable type int, but it isn`t. What is wrong?

Your expectation is wrong. The behaviour of signed integer overflow is undefined. There is no requirement for the answer to be "incorrect". After all, there is no "correct" answer for a program that has undefined behaviour.

Upvotes: 2

Related Questions