user10446161
user10446161

Reputation:

Swap in C - Printing

I just implemented my swap function but it does not print anything. Do you know why does the line printf does not execute?

#include <stdio.h>
int swap(int x, int y) {
    scanf("%d", &x);
    printf("%d, x is",x);
    scanf("%d", &y);

    int temp = x;
    x = y;
    y = temp;
    printf("After Swapping: x = %d, y = %d", x, y);
    return 0;
}
int main() {
    swap(6,5);
}

Upvotes: 0

Views: 236

Answers (2)

haccks
haccks

Reputation: 106022

You should not take user input inside the swap function. Its purpose should be to swap two integers only. You can move the scanf statements to main function.

#include <stdio.h>

int swap(int x, int y){
    int temp = x;
    x = y;
    y = temp;
    printf("After Swapping in swap function: x = %d, y = %d", x, y);
    return 0;
}

int main(void){
    int x, y;
    scanf("%d", &x);
    printf("%d, x is", x);
    scanf("%d", &y);
    printf("%d, y is", y);
    swap(x, y);
    printf("After Swapping in main function: x = %d, y = %d", x, y);
}

But the above code has a major issue. Though the swap function prints the integers passed as they are swapped but the fact is x and y in the main remains unaffected.

In this case to make it work, using pointers would be helpful

void swap(int *ptrx, int *ptry){
    int temp = *ptrx;
    *ptrx = *ptry;
    *ptry = temp;
}

In the main function call the swap as swap(&x, &y);

Upvotes: 2

GameChanger
GameChanger

Reputation: 179

Use this code for swapping.

#include <stdio.h>
void swap(int x, int y)
{
    int z;
    z = x;
    x = y;
    y = z;
    printf("After Swapping: x = %d, y = %d", x, y);        
}
int main()
{
    swap(6,5);
    return 0;
}

And I don't understand why you need to scan x & y

Upvotes: 1

Related Questions