Search code examples
c++floating-pointintegerexponentialstatic-cast

Exponential Shorthand for Integers


So my understanding is that this: 1e3 Equates to 1000.0.

My question is, is there a similar shorthand for integers? I realize that I can do: static_cast<int>(1e3). Is there anything available to me outside of this?


Solution

  • No, there is no syntax for scientific notation integer literal in C++.

    You could shorten the conversion with a user defined literal:

    constexpr int operator "" _i(long double d) noexcept {
        return d;
    }
    
    int main() {
        auto big = 1e3_i; // is int
    }
    

    However, this does (at least on GCC that I tested) prevent the compiler from noticing overflow in the initialization so in those cases where possible, prefer the more conventional:

    int big = 1e30; // compiler should yell at you