I'm using the book Programming -- Principles and Practice Using C++ by Bjarne Stroustrup and I'm having some difficulty with the definition of expression. Here is an excerpt from the book:
The most basic building block of programs is an expression. An expression computes a value from a number of operands. The simplest expression is simply a literal value, such as 10, 'a', 3.14, or "Norah". Names of variables are also expressions.
Then the author begins to talk about about lvalues and rvalues. I can't understand why a variable name is considered an expression, because it has neither operands nor operators. What do lvalues and rvalues have to do with that? How can be the name of a variable be an expression in a statement like a = 10?
It makes it easier to describe the parsing rules if you consider everything that gives you a value an expression.
Addition could be seen as two expressions with a + sign in between:
1. exp + exp
If a variable name was not an expression you would have to have a few extra rules:
1. exp + exp
2. variable + exp
3. exp + variable
4. variable + variable
And if you don't consider literals expressions you would have to have even more rules.
It makes it easier to describe the parsing rules if you consider everything that gives you a value an expression.
Addition could be seen as two expressions with a + sign in between:
1. exp + exp
If a variable name was not an expression you would have to have a few extra rules:
1. exp + exp
2. variable + exp
3. exp + variable
4. variable + variable
And if you don't consider literals expressions you would have to have even more rules.
@Peter87 why my book explain me the difference between lvalue and rvalue ?
I'm no expert on lvalues and rvalues but as I understand it a lvalue is an expression that you can put on the left side of an assignment. rvalues can only be put on the right side of an assignment.
1 2
int a;
a = 1 + 2;
Here a is a lvalue because you can assign a value to it . 1 + 2 is a rvalue because you can't assign a value to it.
An lvalue doesn't have to be just a variable name. It can be a function call returning a reference.
1 2 3 4 5 6 7 8 9 10
int& foo()
{
staticint bar = 0;
return bar;
}
int main()
{
foo() = 1; // sets the static variable bar in foo() to 1.
}
Another example is when assigning a value to an array element using the subscript operator or pointer syntax.
1 2 3 4 5 6 7 8
int main()
{
int arr[] = {1, 2, 3};
// Two ways of setting the third value of the array to 1:
arr[2] = 1; // Using the subscript operator.
*(arr + 2) = 1; // Using pointer syntax.
}