c++ - Does typecasting consume extra CPU cycles -


does typecasting in c/c++ result in cpu cycles?

my understanding is should consume cpu cycles atleast in cases. typecasting float integer cpu should require convert float structure integer.

float a=2.0; int b= (float)a; 

i understand cases would/would not consume cpu cycles.

i "converting between types" should looking at, not whether there cast or not. example

 int = 10;  float b = a;  

will same :

 int = 10;  float b = (float)a; 

this applies changing size of type, e.g.

 char c = 'a';  int b = c;  

this "extend c int size single byte [using byte in c sense, not 8-bit sense]", potentially add instruction (or clockcycle(s) instruction used) above , beyond datamovement itself.

note these conversions aren't @ obvious. on x86-64, typical example using int instead of unsigned int indices in arrays. since pointers 64-bit, index needs converted 64-bit. in case of unsigned, that's trivial - use 64-bit version of register value in, since 32-bit load operation zero-fill top part of register. if have int, negative. compiler have use "sign extend 64 bits" instruction. typically not issue index calculated based on fixed loop , values positive, if call function not clear if parameter positive or negative, compiler have extend value. likewise if function returns value used index.

however, reasonably competent compiler not mindlessly add instructions convert own type (possibly if optimization turned off, may - minimal optimization should see "we're converting type x type x, doesn't mean anything, lets take away").

so, in short, above example not add penalty, there cases "converting data 1 type add instructions and/or clockcycles code".


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -