-4

I'm a beginner in C++ so please bear with me. Below is just a part of the full program.

When the user inputs the first number (assume '3'), it goes to the if statement. a[count ++] then becomes a[1] (if I'm not wrong, because count is initially 0). The array element a[1] thus stores the input which is 3. If so, then didn't the program just skip a[0]?

int readarray(int a[], int capacity) {
int count = 0; 
    int input; 
    do {
        cout << "Enter a number (-1 to stop):  "; 
        cin >> input; 
        if (input != -1) {
            a[count++] = input; 
        }
    } while (input != -1 && count << capacity); 
    return count; 
melpomene
  • 84,125
  • 8
  • 85
  • 148
Achyut
  • 19
  • 1
  • 4

3 Answers3

6

Because count++ is a post increment operator. It uses the current value of count in the expression and also increments count. It's not defined how or when the increment happens so any other uses of count in the same statement could have unexpected results.

The statement is equivalent to writing

a[count] = input;
count = count + 1;

As a matter of personal opinion I think you should never use the pre/post increment/decrement operators in an expression. It doesn't produce any more efficient code, it is rather less readable and tends to end up with off by one errors.

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61
  • "*It returns the value of count then increments it*" is not entirely correct. It could also increment first, then return count-1 (the old value of count). Or it could interleave the two actions. The point is, no such temporal ordering is implied. – melpomene Jun 18 '16 at 08:58
  • @AlanStokes - arggh, sorry, it's too early in the morning – Tom Tanner Jun 18 '16 at 09:00
  • @melpomene - true. clarified – Tom Tanner Jun 18 '16 at 09:00
  • Now it's less wrong but also less clear, I think. "*... and also increments it*" can be read as referring to "value". And your "equivalent" rewrite still shows an ordering. – melpomene Jun 18 '16 at 09:02
  • @melpomene re-re-correct while you were commenting. – Tom Tanner Jun 18 '16 at 09:04
  • You don't really "return" anything, because we're talking about an expression, not a jump statement. Evaluated expressions have values, and expression evaluation can have side effects. The value of the expression `x++` is the original value of `x` (and it is an rvalue), and the side effect is that `x` is incremented. – Kerrek SB Jun 18 '16 at 09:26
4

No, postfix increment (x++) returns the old value of the variable. So a[count++] increments count from 0 to 1, but uses 0 (the old value of count) as the index.

By the way, count << capacity looks wrong. Did you mean count < capacity?

melpomene
  • 84,125
  • 8
  • 85
  • 148
-2

Instead of a[count++] you can do if(input != -1){a[count] = input; count++}. In this way the value will be assigned to current array index say at start, it will be assigned to a[0] and then count will be incremented to 1. So next iteration will have a[1].