Search code examples
c++post-incrementpre-increment

How does this code work?


I am looking at c++ for dummies and found this code

#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

int nextStudentId = 1000; // first legal Student ID
class StudentId
{
public:
StudentId()
{
    value = nextStudentId++;
    cout << "Take next student id " << value << endl;
}

// int constructor allows user to assign id
StudentId(int id)
{
    value = id;
    cout << "Assign student id " << value << endl;
}
protected:
int value;
};

class Student
{
public:
Student(const char* pName)
{
     cout << "constructing Student " << pName << endl;
     name = pName;
     semesterHours = 0;
     gpa = 0.0;
 }

protected:
string    name;
int       semesterHours;
float     gpa;
StudentId id;
};

int main(int argcs, char* pArgs[])
{
// create a couple of students
Student s1("Chester");
Student s2("Trude");

// wait until user is ready before terminating program
// to allow the user to see the program results
system("PAUSE");
return 0;
}

this is the output

Take next student id 1000

constructing Student Chester

Take next student id 1001

constructing Student Trude

Press any key to continue . . .

I am having a really hard time of understanding why the first student id is 1000 if value adds one to it and then prints it out

does this make sense

right in the constructor for studentId the two lines of code take nextStudentId and add one to it then it gets printed out

wouldn't the output be something like this:

Take next student id 1001

constructing Student Chester

Take next student id 1002

constructing Student Trude

Press any key to continue . . .

hope you get what I am trying to say

thanks

Luke


Solution

  • The ++ is the post-increment operator: it first reads the value (and assigns it to a variable), and only then increments it.

    Contrast this with the pre-increment operator:

    value = ++nextStudentId;
    

    This would have the behavior you expect.

    Take a look at this question for more information: Incrementing in C++ - When to use x++ or ++x?