Home > front end >  How many levels of explicit casting?
How many levels of explicit casting?

Time:01-31

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?

CodePudding user response:

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.

CodePudding user response:

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

Zero levels of casting is needed, if you use implicit conversion instead:

int n = 46341;
long long nl = n;
long long value = ((nl * (nl   1))) / 2;

CodePudding user response:

In this statement

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

there are too many redundant castings.

You could just write for example

long long value = n * ( n   1LL ) / 2;

or

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

Here is a demonstration program.

#include <iostream>

int main()
{
    int n = 46341;

    long long value = n * ( n   1LL ) / 2;

    std::cout << "value = " << value << '\n';

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

    std::cout << "value = " << value << '\n';
}

The program output is

value = 1073767311
value = 1073767311

That is it is enough to use one of operands of the expression of the type long long and other operands will be implicitly converted to this type due to the usual arithmetic conversions.

  •  Tags:  
  • Related