83

I have an int pointer (i.e., int *count) that I want to increment the integer being pointed at by using the ++ operator. I thought I would call:

*count++;

However, I am getting a build warning "expression result unused". I can: call

*count += 1;

But, I would like to know how to use the ++ operator as well. Any ideas?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
joels
  • 7,249
  • 11
  • 53
  • 94

2 Answers2

114

The ++ has equal precedence with the * and the associativity is right-to-left. See here. It's made even more complex because even though the ++ will be associated with the pointer the increment is applied after the statement's evaluation.

The order things happen is:

  1. Post increment, remember the post-incremented pointer address value as a temporary
  2. Dereference non-incremented pointer address
  3. Apply the incremented pointer address to count, count now points to the next possible memory address for an entity of its type.

You get the warning because you never actually use the dereferenced value at step 2. Like @Sidarth says, you'll need parenthesis to force the order of evaluation:

 (*ptr)++
Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
Doug T.
  • 64,223
  • 27
  • 138
  • 202
  • 10
    I'd add that I always write this case as `++*ptr;` because the precedence is unambiguous, and if the result isn't used there is no need to distinguish between preincrement and postincrement. – RBerteig Sep 07 '10 at 06:52
  • 6
    @RBerteig: It may be unambiguous to the compiler but it is still confusing to a human. Much better to use parenthesis as this will make it easier to read. – Martin York Sep 07 '10 at 11:37
  • 1
    @Martin, over use of parenthesis can be just as confusing to a human. When written as I did, there is only one plausible order of operations, and matches the natural reading of "increment", "something pointed to by", "p". – RBerteig Sep 07 '10 at 18:41
  • 2
    @RBerteig: If you are claiming that `++*ptr` is easier to read than `++(*ptr)` then I hope you get slapped down in your next code review. – Martin York Sep 07 '10 at 18:56
  • 2
    I do so claim, and have for ~25 years. No slaps yet. – RBerteig Sep 07 '10 at 22:09
  • I did slap someone recently for writing `!(!(foo))`. There *is* such a thing as too many parentheses. – RBerteig Sep 07 '10 at 22:09
  • 12
    @RBerteig: Half a century of Lisp disagrees with you. ;) – Deniz Dogan Sep 22 '10 at 13:00
21

Try using (*count)++. *count++ might be incrementing the pointer to next position and then using indirection (which is unintentional).

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
Sidharth Panwar
  • 4,606
  • 6
  • 27
  • 36