Search code examples
cpointerspass-by-referencedifference

Pointer value difference not as expected


Why does the following code display 4-5 as 4 and not -1?

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int fun(int *a, int *b){
  *a = *a+*b;
  *b = *a-*b;
}

void main(){
  int a=4;
  int b=5;
  int *p=&a, *q=&b;
  fun(p,q);
  printf("%d\t%d",a,b);
}

The sum comes as 9 (as expected), but why does the difference come as 4?


Solution

  • This assigns the result of *a + *b to *a, so after

    *a = *a + *b; // 4 + 5
    

    then *a is 9, so

    *b = *a - *b;
    

    makes it *b = 9 - 5, which is 4.

    The problem has nothing to do with pointers. You would have the same problem if you did it without:

    int a = 4;
    int b = 5;
    a = a + b; // assign the result of 4 + 5 (9) to a
    b = a - b; // assign the result of 9 - 5 (4) to b
    

    Also note that the program has undefined behavior since fun is declared to return an int but it doesn't return anything.