Odd behavior with initilization.

I am trying to have id1 be one step ahead of count(number-wise). I was trying to accomplish this with the prefix version of the increment operator, but this produced odd behavior.

What I planned on happening was 1. count would be initialized to zero. 2. id1 would be initialized to ++count( which due to the the prefix increment operator would be incremented before id1 was set to its value making id1 equal one while count still equaled zero.) 3. I would print count.

When I printed count, however, I found out that the code id1(++count) was incrementing count as well as setting id1 to ++count.

Why does this happen? It seems inconvenient for setting values for ints to also increment other variables in the process. How do I avoid this? Can I write it in such a way that it still displays that my intent for it to be one higher than count or is that just not possible?

Main file:

1
2
3
4
5
6
7
8
9
10
11
12
13
  
#include <iostream>
#include "Count.h"

using namespace std;

int main() {
	Count test1;
	test1.information();

	return 0;
}


.ccp file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include "Count.h"

int Count::count = 0;

Count::Count() : id1(count+1) {
	count++;
};

Count::~Count() {

}

void Count::information(){
	cout << Count::count << endl;
};

void Count::id(){
		cout << id1 << endl;
	};


.h file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#ifndef COUNT_H_
#define COUNT_H_

#include <iostream>

using namespace std;

class Count {
public:
	static int count;
	int id1;
public:
	void information();
	void id();
	Count();
	virtual ~Count();
private:

};

#endif /* COUNT_H_ */
Consider this program:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
int main() 
{
  int x = 4;
  std::cout << ++x << ' ';
  std::cout << x << '\n';

  int y = 8;
  std::cout << y++ << ' ';
  std::cout << y << '\n';
}

Its output is
5 5
8 9
Last edited on
There is a difference between pre-inc and post-inc (same for pre-dec and post-dec).

pre-inc (++i) first increments i and then returns the new value of i as the result of the expression. So z = ++i first increments i and this incremented value is then assigned to z

post-inc (i++) returns the current value of i for the result of the expression and then increments i. So z = i++ assigns the current value of i to z and then increments i.

If the result of the expression is not used, then logically there is no difference between pre-inc and post inc. These only have different outcomes if the result is used.

If you have a choice (ie the result isn't used), then choose pre-inc. For a POD type, this has no difference but for some classes, using a post-inc incurs an extra copy which could impact performance.
Topic archived. No new replies allowed.