Home > OS >  Pointer not incrementing in printf statement?
Pointer not incrementing in printf statement?

Time:12-17

How come this piece of code

#include <stdio.h>

int main(){
  int y=42;
  int *p=&y;
  (*p)  ;
  printf("%d\n",*p);
  return 0;
}

outputs 43, as expected, but this piece of code

#include <stdio.h>

int main(){
  int y=42;
  int *p=&y;
  printf("%d\n",(*p)  );
  return 0;
}

outputs 42?

CodePudding user response:

x is the post-increment operator. It increments the variable it's called on, but evaluates to the value before the increment.

Breaking the printf statement up to two statements may make it clearer:

int pBeforeIncrement = (*p)  ; // After this statement, pBeforeIncrement   1 == p
printf("%d\n", pBeforeIncrement);

CodePudding user response:

  printf("%d\n",(*p)  );

It increments the value after passing the value to the print. It is called postincrement.

  printf("%d\n",  (*p));

It increments the value before passing the value to the print. It is called preincrement.

int main(){
  int y=42;
  int *p=&y;
  printf("(*p) = %d\n",(*p));
  printf("(*p)   = %d\n",(*p)  );
  printf("(*p) = %d\n",(*p));
  printf("  (*p) = %d\n",  (*p));
  return 0;
}

https://godbolt.org/z/Ke5Y6e3q8

  • Related