Search code examples
c++castingimplicit-conversionliterals

How many levels of explicit casting?


Code snippet #1.

int n = 46341;
long long value = ((long long) (n * (n + 1))) / 2;
std::cout << value; // -1073716337 -- WRONG!

Code snippet #2.

int n = 46341;
long long value = (long long)((long long)((long long)n * ((long long)n + 1))) / 2;
std::cout << value; // 1073767311 -- CORRECT!

How many levels of explicit casting are necessary to produce the desired result?


Solution

  • One. As a general rule, the result of an arithmetic expression will take the type of the larger of the two.

    long long value = (n * (static_cast<long long>(n) + 1)) / 2;
    

    So (long long)n + 1 is addition of a long long and an int, so the result is long long. Then n * (...) is multiplication of an int and a long long, so again we take the bigger, and so on.

    But, as pointed out in the comments, you should probably make a temporary so as to separate the casting shenanigans from the actual math.

    long long n0 = n;
    long long value = (n0 * (n0 + 1)) / 2;
    

    Now there's two lines: one casts the variable to a larger type and the other is purely mathematical. It's much more readable at a glance.

    Note: I use static_cast rather than the old C-style syntax. You can find several questions on StackOverflow and its sister sites on why this is a good idea, so I won't repeat that reasoning here other than to point out that it is a good idea.