0

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?

Kim Minseo
  • 81
  • 7

3 Answers3

2

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).

Jasmeet
  • 1,315
  • 11
  • 23
1

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

hotoku
  • 151
  • 9
0

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)++;

Gilad
  • 305
  • 1
  • 2
  • 8