Andrew Tomazos
Andrew Tomazos

Reputation: 68588

C++11 type of variable in expression?

In C++11 I'm somewhat confused about the difference between the types T and reference to T as they apply to expressions that name variables. Specifically consider:

int main()
{
    int x = 42;
    int& y = x;

    x; // (1)
    y; // (2)
}

What is the type of the expression x in (1) in the above? Is it int or lvalue reference to int ? (Its value category is clearly an lvalue, but this is separate from its type)

Likewise what is the type of the expression y at (2) in the above? Is it int or lvalue reference to int ?

It says in 5.1.1.8:

The type of [an identifier primary expression] is the type of the identifier. The result is the entity denoted by the identifier. The result is an lvalue if the entity is a function, variable, or data member and a prvalue otherwise.

Upvotes: 3

Views: 565

Answers (2)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

The bit you're missing is this (§5/5):

If an expression initially has the type “reference to T” (8.3.2, 8.5.3), the type is adjusted to T prior to any further analysis.

So although the identifier y has type int&, the expression y has type int. An expression never has reference type, so the type of both of your expressions is int.

Upvotes: 10

The expression denotes an lvalue of type int, in both cases. An expression cannot be a reference, although you can bind the result of an expression with an lvalue or rvalue reference.

Upvotes: 3

Related Questions