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?

cryolock
  • 45
  • 6

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,239
  • 8
  • 18
1

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

hotoku
  • 162
  • 7
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
  • 315
  • 1
  • 2
  • 8