Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize unsigned int to 0?

Tags:

c++

c++11

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?

like image 870
Allanqunzi Avatar asked Dec 02 '22 13:12

Allanqunzi


1 Answers

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.

like image 125
Jesper Juhl Avatar answered Jan 01 '23 05:01

Jesper Juhl