Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is primitive casting, creates a new object in memory?

My question is simple, if I have the following code in C++:

int main(int argc, const char * argv[])
{
    int i1 = 5;
    int i2 = 2;
    float f = i1/(float)i2;
    std::cout << f << "\n";

    return 0;
}

Is (float)i2 going to create a new object in memory that is next going to devide i1 and assigned on f or the casting operator is somehow translating (float)i2 on the fly and do the devision with not extra memory for the casting?

Also, what is going on with cases that casting requires different sizes of variables? (e.g. from float to double)

like image 333
Anastasios Andronidis Avatar asked Sep 04 '14 12:09

Anastasios Andronidis


Video Answer


1 Answers

Is (float)i2 going to create a new object in memory

The cast creates a temporary object, which will have its own storage. That's not necessarily in memory; a small arithmetic value like this is likely to be created and used in a register.

Also, what is going on with cases that casting requires different sizes of variables?

Since a new object is created, it doesn't matter whether that they have a different size and representation.

like image 104
Mike Seymour Avatar answered Sep 17 '22 01:09

Mike Seymour