c++ types,

D31a66e3daa66f418c961ed74ece9b7b
0
kruseborn 101 Dec 02, 2009 at 13:10

What is the different when writing for example unsigned i = 0; and unsigned i = 0u; Does the compiler compile this two examples different?

The same question regarding big numbers, when for example long long i = 1LL << 35;

Should you always tell the compiler what kind of type you are using?

5 Replies

Please log in or register to post a reply.

B7568a7d781a2ebebe3fa176215ae667
0
Wernaeh 101 Dec 02, 2009 at 13:30

See this discussion:

http://stackoverflow.com/questions/436300/are-constant-c-expressions-evaluated-at-compile-time-or-at-runtime

As a short summary, your compiler is free to evaluate these constant expressions either at compile time or at runtime.

However, your compiler needs to at least evaluate the types of a given constant expression to provide compile-time typing errors.

Thus most compilers automatically perform the appropriate calculations as well for optimization purposes.

Thus,
long long i = 1LL << 35;
commonly is precalculated, but may also be explicitly calculated on weird compilers.

Just have a look at your compiler output for the appropriate line for the actual behaviour.

I generally don’t bother with providing constant type specifiers, since I think code is more readable without them. However, I add them whereever required to solve typing problems.

I.e.
float myValue = 1;
But:
float myValueToo = MyInteger / 7.f;

Hope this helps,
Cheers,
- Wernaeh

36b416ed76cbaff49c8f6b7511458883
0
poita 101 Dec 02, 2009 at 13:35

There is no difference. The compiler automatically converts them to the type you need.

The difference comes in when calling templated/overloaded functions.

e.g.

void foo(int i) {cout << "int" << endl;}
void foo(unsigned int i) {cout << "unsigned int" << endl;}

int main()
{
  foo(0); // prints "int"
  foo(0U); // prints "unsigned int"
}
D31a66e3daa66f418c961ed74ece9b7b
0
kruseborn 101 Dec 02, 2009 at 13:36

Thank you

D31a66e3daa66f418c961ed74ece9b7b
0
kruseborn 101 Dec 02, 2009 at 13:53

Well it is a different,
this code print different outputs:

#include <iostream>

using namespace std;

int main()
{
    long long temp = 1LL<<35;
    long long temp2 = 1<<35;
    cout << temp << endl;
    cout << temp2 << endl;
    return 0;
}

@poita

There is no difference. The compiler automatically converts them to the type you need.

The difference comes in when calling templated/overloaded functions.

e.g.

void foo(int i) {cout << "int" << endl;}
void foo(unsigned int i) {cout << "unsigned int" << endl;}

int main()
{
  foo(0); // prints "int"
  foo(0U); // prints "unsigned int"
}
36b416ed76cbaff49c8f6b7511458883
0
poita 101 Dec 02, 2009 at 14:28

Yes, it will matter in that case because you have an expression that will be evaluated as an int. 1<<35 cannot be represented as an int, so you get garbage. You need to promote the 1 to a long long so that it will be evaluated correctly.