Search code examples
c++scopeexplicit-conversion

c++ explicit type cast gives wrong answer


Why would I be getting an int conversion to float wrong in c++? At a point in a program I am explicitly converting an integer with value 10 or 14 to float, and I get 0. Why would that be ? I tried static_cast, gives me same result. Since both int and float are 4 bytes, I am thinking int to float conversion is not a demotion or promotion by size ? Is it related to rounding errors etc ? Can someone please explain.

Here is the code( There is an alteration here which works fine, but I still don't know why) ---

#include <iostream>
using namespace std;

int main()
{

int n;
int sum;

cout << "Please enter the number:";
cin >> n;

int *elements = new int[n];

cout << "Please enter the elements:";
for(int i=0; i<n; i++)
{
   cin >> elements[i];
}
cout << endl;

///// this approach, gives the sum right, but float(sum) fails and always gives zero.

for(int i=0, sum=0; i < n; i++)
{
   sum = sum + elements[i];
}

////// This works, when sum is initialised outside of for loop. float(sum) does the right conversion as well.
//sum = 0;
//for(int i=0; i < n; i++)
//{
//   sum = sum + elements[i];
//}

cout << " float n is " << float(n) << " float sum is "<< float(sum) << endl;
// float(sum) is zero, when sum is initialised from within for loop.

delete[] elements;

return 0;
}

command to compile -> g++ 3.2.cpp -o 3.2

Inputs: n = 4; elements = 1 2 3 4

It feels like something minor that I am overlooking.

Thanks for the help.


Solution

  • You've got two different sum variables. The sum you're initializing in the for loop is actually scoped to the for loop, just like the i counter. When you do for (int i = 0, sum = 0; ... you're creating two new variables, i and sum, for the loop. Thus, the sum variable you're updating in the for-loop is not the sum variable you think it is (it's shadowing the sum variable you want).

    This is why it's important to post your real, actual code from the start. Little details like this matter a lot.