⚙️ C++ Intermediate

What are lvalues and rvalues in C++?

Why Interviewers Ask This

Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.

Answer

Value categories classify expressions in C++. Understanding them is essential for move semantics. Lvalue (locator value): an expression that identifies a persistent object with a memory address — can appear on the left side of assignment. int x = 42; // x is an lvalue int& ref = x; // Can take address: &x std::string s = "hello"; // s is an lvalue s = "world"; // OK -- persistent object int arr[5]; arr[2] = 10; // arr[2] is an lvalue. Rvalue (right-hand value): a temporary expression with no persistent memory address — appears on the right side, cannot be assigned to. int y = 42 + 8; // 42+8 is rvalue (temporary) std::string s = std::string("temp"); // "temp" literal + string() are rvalues &42; // ERROR -- can't take address of rvalue. Rvalue reference (&&): binds specifically to rvalues, enabling move semantics: int&& rref = 42; // Binds to rvalue -- extends lifetime void func(int&& x) { /* only called with rvalue */ }. C++11 value categories (full picture): lvalue (named variables, dereferenced pointers), prvalue (pure rvalue — literals, temporaries), xvalue (eXpiring value — std::move result), glvalue (generalized lvalue = lvalue or xvalue), rvalue (prvalue or xvalue). Reference binding rules: lvalue reference (T&) binds to lvalues; const lvalue reference (const T&) binds to both lvalues and rvalues (extends lifetime of temporaries!); rvalue reference (T&&) binds to rvalues. Practical implication: when you pass a named variable to std::move(), it becomes an xvalue — the object remains alive but signals "you can steal my resources."

Common Mistake

Don't just define the term — demonstrate that you understand when to use it and when not to. Showing awareness of trade-offs is what separates average from strong C++ candidates.