Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`#define` a very large number in c++ source code

Well, the question is not as silly as it sound.

I am using C++11 <array> and want to declare an array like this:

array<int, MAX_ARR_SIZE> myArr;

The MAX_ARR_SIZE is to be defined in a header file and could be very large i.e. 10^13. Currently I am typing it like a pre-school kid

 #define MAX_ARR_SIZE 1000000000000000

I can live with it if there is no alternative. I can't use pow(10, 13) here since it can not be evaluated at compile time; array initialization will fail. I am not aware of any shorthand to type this.

like image 964
Dilawar Avatar asked Nov 30 '22 16:11

Dilawar


2 Answers

Using #define for constants is more a way of C than C++.

You can define your constant in this way:

const size_t MAX_ARR_SIZE(1e15); 
like image 156
Tomáš Šíma Avatar answered Dec 04 '22 03:12

Tomáš Šíma


In this case, using a const size_t instead of #define is preferred.


I'd like to add that, since C++14, when writing integer literals, you could add the optional single quotes as separator.

1'000'000'000'000'000

This looks more clear.

like image 26
Yu Hao Avatar answered Dec 04 '22 03:12

Yu Hao