Kim Minseo
Kim Minseo

Reputation: 81

Increment function with pointers not working

I am trying to find the number of digits in a given number through the use of pointers.

This code below will give the correct output,

void numDigits(int num, int *result) {
  *result = 0;

  do {
    *result += 1;
    num = num / 10;
  } while (num > 0);
}

However, if I change the *result += 1; line to *result++;, the output will no longer be correct and only give 0.

What is going on here?

Upvotes: 0

Views: 67

Answers (3)

Jasmeet
Jasmeet

Reputation: 1460

In C/C++, precedence of Prefix ++ (or Prefix --) has higher priority than dereference (*) operator, and precedence of Postfix ++ (or Postfix --) is higher than both Prefix ++ and *.

If p is a pointer then *p++ is equivalent to *(p++) and ++*p is equivalent to ++(*p) (both Prefix ++ and * are right associative).

Upvotes: 2

hotoku
hotoku

Reputation: 141

*result++ is interpreted as *(result++).

Upvotes: 1

Gilad
Gilad

Reputation: 305

the order of evaluation is the increment is first, then you dereference the pointer, the value of the pointer stays the same for the line in the expression if it's a postfix. what you are trying to do is to increment the dereference of the pointer so you need to put the parenthesis on the dereference then increment it, like this: (*result)++;

Upvotes: 0

Related Questions