Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is an enum variable an rvalue here?

Example:

typedef enum Color
{
    RED,
    GREEN,
    BLUE
} Color;

void func(unsigned int& num)
{
    num++;
}

int main()
{
    Color clr = RED;
    func(clr);
    return 0;
}

I get the following error when I compile this:

<source>: In function 'int main()':

<source>:16:9: error: cannot bind non-const lvalue reference of type 'unsigned int&' to an rvalue of type 'unsigned int'

     func(clr);

         ^~~

I think the variable (clr) I pass to func(unsigned int&) is an lvalue. I can get the address of clr and can assign another value to it. Why does it turn into an rvalue when I try to pass it to func(unsigned int&)?

like image 412
Koen Avatar asked Dec 31 '19 07:12

Koen


People also ask

Are enum values signed or unsigned?

An enum type is represented by an underlying integer type. The size of the integer type and whether it is signed is based on the range of values of the enumerated constants. In strict C89 or C99 mode, the compiler allows only enumeration constants with values that will fit in "int" or "unsigned int" (32 bits).

Is an enum an int?

The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.

Why enum is used in CPP?

In C++ programming, enum or enumeration is a data type consisting of named values like elements, members, etc., that represent integral constants. It provides a way to define and group integral constants. It also makes the code easy to maintain and less complex.

Is an rvalue reference an rvalue?

An rvalue reference can only bind to an rvalue (without a static_cast being involved), but it is otherwise an lvalue of type rvalue reference. The fact it is of type rvalue reference only matters during its construction, and if you do decltype(variable_name) . It is otherwise just another lvalue of reference type.


1 Answers

clr itself is an lvalue of type Color. But the function does not accept a Color. It accepts a (reference to) unsigned int. So, the argument is converted (implicitly). And the result of the conversion is a prvalue of type unsigned int.

like image 92
eerorika Avatar answered Oct 17 '22 23:10

eerorika