Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it safe to bind an unsigned int to a signed int reference?

After coming across something similar in a co-worker’s code, I’m having trouble understanding why/how this code executes without compiler warnings or errors.

#include <iostream>

int main (void)
{
    unsigned int u = 42;

    const int& s = u;

    std::cout << "u=" << u << " s=" << s << "\n";

    u = 6 * 9;

    std::cout << "u=" << u << " s=" << s << "\n";
}

Output:

u=42 s=42
u=54 s=42

First, I expect the compiler to issue some kind of diagnostic when I mix signed/unsigned integers like this. Certainly it does if I attempt to compare with <. That’s one thing that confuses me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Second, I’m not sure how the second line of output is generated. I expected the value of s to be 54. How does this work? Is the compiler creating an anonymous, automatic signed integer variable, assigning the value of u, and pointing the reference s at that value? Or is it doing something else, like changing s from a reference to a plain integer variable?

>Solution :

References can’t bind to objects with different type directly. Given const int& s = u;, u is implicitly converted to int firstly, which is a temporary and then s binds to the temporary int. (Lvalue-references to const (and rvalue-references) could bind to temporaries.) The lifetime of the temporary is prolonged to the lifetime of s, i.e. it’ll be destroyed when get out of main.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading