Dr.PB
Dr.PB

Reputation: 1067

const vs #define (strange behavior)

I used to replace const with #define, but in the below example it prints false.

#include <iostream>
#define x 3e+38

using namespace std;

int main() {
    float p = x;
    if (p==x)
        cout<<"true"<<endl;
    else
        cout<<"false"<<endl;
return 0;
}

But if I replace

#define x 3e+38

with

const float x = 3e+38;

it works perfectly, question is why? (I know there are several topics discussed for #define vs const, but really didn't get this, kindly enlighten me)

Upvotes: 5

Views: 129

Answers (2)

vsb
vsb

Reputation: 11

The number 3e+38 is double due its magnitude.

The assignment

float p = x; 

causes the 3e+38 to lose its precision and hence its value when stored in p.

thats why the comparison :

if(p==x)

results in false because p has different value than 3e+38.

Upvotes: 1

Ari Hietanen
Ari Hietanen

Reputation: 1769

In c++ the literals are double precision. In the first examples the number 3e+38 is first converted to float in the variable initialization and then back to double precision in the comparison. The conversions are not necessary exact, so the numbers may differ. In the second example numbers stay float all the time. To fix it you can change p to double, write

#define x 3e+38f

(which defines a float literal), or change the comparison to

if (p == static_cast<float>(x))

which performs the same conversion as the variable initialization, and does then the comparison in single precision.

Also as commented the comparison of floating point numbers with == is not usually a good idea, as rounding errors yield unexpected results, e.g., x*y might be different from y*x.

Upvotes: 5

Related Questions