Contents
increment(++)/decrement(--) operators
- unary operators
- 2 modes:
- postfix (operator follows operand)
E.g.,AخAx--;
- prefix (operator precedes operand)
E.g.,--x;
- postfix (operator follows operand)
- Examplex
for (int i=0; i<10; ++i)
- increment
- increase by one
- decrement
- decrease by one
- Different syntax, same semantics
x = x + 1;
x += 1;
++x;
x++;
- increment and decrement operators
- Examples
using namespace std;
int main()
{
for (int i=0; i<10; ++i) {
cout << i << endl;
}
int x = 5;
cout << x << endl; // 5
cout << x++ << endl; // 5
cout << x << endl; // 6
int y = 5;
cout << y << endl; // 5
cout << ++y << endl; // 6
cout << y << endl; // 6
return 0;
}
lvalue and rvalue
- A C++ expression is either an lvalue or an rvalue
- lvalue (locator value)
- has an identity (i.e., an address that is accessible though code)
- all variables, even those marked with const; a variable that is not const is called a modifiable lvalue
- persists after the evaluation of a single expression
- rvalue
- any expression that is not an lvalue
- cannot be referred to (does not have an identity)
- temporary values for intermediate values in a computation are often rvalues
- does not persist after the evaluation of the expression that uses it
- More in-depth description (will not be on the final exam)
-
using namespace std;
int& return_by_reference(int& arg)
{
return arg;
}
int main()
{
int x = 1;
// 1 = x; // error: lvalue required as left operand of assignment
return_by_reference(x) = 2; // valid - lvalue returned from function
cout << x << endl;
const int y = 3; // valid - initialized y
//y = 4; // error: assignment of read-only (lvalue) variable
//cout << &(&y) << endl // error: lvalue required as unary ‘&’ operand
int a, b;
((y < 3) ? a : b) = 7; // valid - conditional evaluates to an lvalue
return 0;
}
More on struct
- Introduce new type into the program
- Why not use arrays?
- Example
using namespace std;
int main()
{
ifstream input("students.txt");
for (string line; getline(input, line);) {
string name;
double numeric_grade;
char letter_grade;
double height_in_feet;
stringstream ss(line);
ss >> name;
ss >> numeric_grade;
ss >> letter_grade;
ss >> height_in_feet;
cout << name << " "
<< numeric_grade << " "
<< letter_grade << " "
<< height_in_feet << endl;
}
return 0;
}
In-Class Modifications to struct Example
-
using namespace std;
struct student_info {
string name;
double numeric_grade;
char letter_grade;
double height_in_feet;
};
int main()
{
ifstream input("students.txt");
vector<student_info> all_students;
for (string line; getline(input, line);) {
student_info s;
stringstream ss(line);
ss >> s.name;
ss >> s.numeric_grade;
ss >> s.letter_grade;
ss >> s.height_in_feet;
cout << s.name << " "
<< s.numeric_grade << " "
<< s.letter_grade << " "
<< s.height_in_feet << endl;
all_students.push_back(s);
}
return 0;
}