Allanqunzi
Allanqunzi

Reputation: 3260

initialize unsigned int to 0?

In the code base, I often see people writing

void f(unsigned int){/* some stuff*/ }; // define f here
f(0) // call f later
unsigned int a = 0;
double d = 0;

Initialized number (0 here) not matching the declared type annoys me, if this is performance critical code, does this kind of initialization hurt performance?

EDIT For the downvoters:

I did search before I posted the question, c++ is famous for hidden rules, i didn't know integer promotion rules until someone commented under this question. For people saying "even stupid compiler won't do conversion at run time", here below is an example from this answer

 float f1(float x) { return x*3.14; }            
 float f2(float x) { return x*3.14F; }

These two versions have different performance, and to an unexperienced c++ programmer, I don't see much difference between my question and this example. And C++ is famous for hidden rules and pitfalls, which means intuition sometimes is not right, so why it is getting downvoted to ask a question like this?

Upvotes: 3

Views: 26815

Answers (2)

Slava
Slava

Reputation: 44238

if this is performance critical code, does this kind of initialization hurt performance?

Very unlikely so. Even without any optimization enabled there is no reason for a compiler to generate code to get original value and convert to type of variable instead of initializing by converted representation of that type (if that conversion is necessary). Though this may affect your code if you use new style, that some people recommend to use in modern C++

auto a = 0U; // if you do not specify U then variable type would be signed int

to use this style or not is a subjective question.

For your addition:

float f1(float x) { return x*3.14; }            
float f2(float x) { return x*3.14F; }

this case is quite different. In the first case x is promoted to double calculations with double is used and then result is converted to float, while on the second case float is multiplied by float. Difference is significant - you either convert compile time constant of one type to constant of another or use calculations with that types.

Upvotes: 8

Jesper Juhl
Jesper Juhl

Reputation: 31467

You are right that 0 is an int, not a double (0. would be) nor an unsigned int. This does not matter here though as int is implicitly convertible to those types and 0 can be represented perfectly by both of them. There's no performance implication either; the compiler does it all at compile time.

Upvotes: 10

Related Questions