Why my print statement inside the swap function is giving such output?

51 Views Asked by At
#include <stdio.h>
void swap(int* x, int* y){
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
    printf("The value of x and y inside the function is x = %d and y = %d", x, y);
}
int main()
{
    int x = 2, y =3;
    swap(&x, &y);
    return 0;
}

Output: The value of x and y inside the function is x = 6422300 and y = 6422296

Why the value of x is 6422300 and y is 6422296 inside the function?

#include <stdio.h>
void swap(int* x, int* y){
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
    printf("The value of x and y inside the function is x = %d and y = %d", x, y);
}
int main()
{
    int x = 2, y =3;
    swap(&x,&y);
    printf("\nThe value of x and y in the main is x = %d and y = %d", x, y);
    return 0;
}

Output: The value of x and y inside the function is x = 6422300 and y = 6422296 The value of x and y in the main is x = 3 and y = 2

I tried to write the print statement for x and y in main separately, then it worked properly. But why it wasn't working inside function?

1

There are 1 best solutions below

1
gulpr On

Your code invoked undefined behaviour as you pass the pointer not the integer to the printf. %d is expecting int. You need to dereference x and y

void swap(int* x, int* y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
    printf("The value of x and y inside the function is x = %d and y = %d\n", *x, *y);
}