Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const vs #define (strange behavior)

Tags:

c++

constants

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)

like image 209
Dr.PB Avatar asked Jan 17 '16 10:01

Dr.PB


People also ask

What is const vs let?

`const` is a signal that the identifier won't be reassigned. `let` is a signal that the variable may be reassigned, such as a counter in a loop, or a value swap in an algorithm. It also signals that the variable will be used only in the block it's defined in, which is not always the entire containing function.

Should I use const or VAR?

As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable. Do not use var.

What does const {} mean in Javascript?

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

What does const {} mean in node JS?

Const is the variables declared with the keyword const that stores constant values. const declarations are block-scoped i.e. we can access const only within the block where it was declared. const cannot be updated or re-declared i.e. const will be the same within its block and cannot be re-declare or update.


1 Answers

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.

like image 79
Ari Hietanen Avatar answered Oct 08 '22 10:10

Ari Hietanen