How to swap integers without using pointers?

1.1k views Asked by At
#include <stdlib.h>
int swap(int a,int b);
int main() {
    int x,y;
    printf("Enter the first integer:"); scanf("%d",&x);
    printf("Enter the second integer:"); scanf("%d",&y);
    printf("\nBefore swap: x=%d, y=%d\n",x,y);
    swap(x,y);
    printf("After swap: x=%d, y=%d",x,y);
    
    return 0;
}

int swap(int a, int b){
        int temp;
        temp = a;
        a=b;
        b=temp;
}

This is my code to swap 2 integers entered by the user but it doesn't work although everything seems to be in order. However if I change my code to this using pointers, it does.

#include <stdlib.h>

int swap(int *,int *);
int main() {
    int x,y;
    printf("Enter the first integer:"); scanf("%d",&x);
    printf("Enter the second integer:"); scanf("%d",&y);
    printf("\nBefore swap: x=%d, y=%d\n",x,y);
    swap(&x,&y);
    printf("After swap: x=%d, y=%d",x,y);
    
    return 0;
}

int swap(int *a, int *b){
        int temp;
        temp = *a;
        *a=*b;
        *b=temp;
}

I would really appreciate if anyone could explain me why and how it worked with pointers but why it didn't without pointers.

5

There are 5 answers

1
Vlad from Moscow On

The first function that shall have the return type void because it returns nothing

void swap(int a, int b){
        int temp;
        temp = a;
        a=b;
        b=temp;
}

deals with copies of values of expressions used as arguments.

You can imagine the function definition and its call the following way

swap(x,y);

//...

void swap( /* int a, int b */){
        int a = x;
        int b = y;
        int temp;
        temp = a;
        a=b;
        b=temp;
}

That is within the function there are swapped the function local variables a and b. The original variables x and y declared in main stay unchanged.

In the second function definition the arguments x and y are passed to the function by reference

swap(&x,&y);

In C passing by reference means passing objects indirectly through pointers to them.

From the C Standard (6.2.5 Types, p. #20)

— A pointer type may be derived from a function type or an object type, called the referenced type. A pointer type describes an object whose value provides a reference to an entity of the referenced type. A pointer type derived from the referenced type T is sometimes called ‘‘pointer to T’’. The construction of a pointer type from a referenced type is called ‘‘pointer type derivation’’. A pointer type is a complete object type.

So dereferencing the pointers (that themselves are passed by value) you get a direct access to the pointed objects that are changed within the function

void swap(int *a, int *b){
        int temp;
        temp = *a;
        *a=*b;
        *b=temp;
}
9
sanskar10100 On

C uses something called pass-by-value. Basically, what happens here, is that the function that is called, in this case swap(), makes its own copies of the arguments that you passed when you called the function. So, when you modify the value of these parameters, namely a and b in the swap() function, you're modifying their value inside the swap() function only, since swap() made its own copy of the arguments.

Try this analogy: You missed a few lectures, and take your friend's notebook to update your notes. Now, suppose you made a few changes in your own notes. Do these changes carry over to your friend's notebook? Obviously not. Similarly, when using pass-by-value, changes made in one function won't have any effect outside the scope of that function.

When you're using pointers though, the values are passed by reference, that is, instead of the values, you're passing the address of the memory locations that holds these values. So, if you make changes to these memory locations themselves through the use of pointers, the values are changed permanently, and the changes are reflected in the caller function too.

0
Randoragon On

In C, every function parameter is passed by value. This means that within the function scope, every argument is just an independent copy of the actual variable being passed to the function. It is impossible to swap two integers by passing them, and not their memory addresses, to a function, because in the function body the values you swap no longer have any connection to the original "outside" variables, other than having the same value.

It is, however, very possible to do what you want without a function:

#include <stdlib.h>

int main() {
    int x,y,temp;
    printf("Enter the first integer:"); scanf("%d",&x);
    printf("Enter the second integer:"); scanf("%d",&y);
    printf("\nBefore swap: x=%d, y=%d\n",x,y);
    temp=x;
    x=y;
    y=temp;
    printf("After swap: x=%d, y=%d",x,y);
    
    return 0;
}

Alternatively, you can write a convenient macro to do that for you. It will behave in a similar fashion to a function:

#include <stdlib.h>

#define swap(x,y) do { \
    int temp=x; \
    x=y; \
    y=temp; \
    } while (0)

int main() {
    int x,y,temp;
    printf("Enter the first integer:"); scanf("%d",&x);
    printf("Enter the second integer:"); scanf("%d",&y);
    printf("\nBefore swap: x=%d, y=%d\n",x,y);
    swap(x,y);
    printf("After swap: x=%d, y=%d",x,y);
    
    return 0;
}

This works and is quite elegant, but be aware that it is not a function and there are possible downfalls to using macros in this way.

10
Emily-TTG On

I would advise looking at the differences between pass-by-reference and pass-by-value on google, but I will summarize here.

Passing by value is when you give a value to a function directly, this value is copied to the function's scope at call. Passing by reference is when, instead of passing the value of a variable, you pass a pointer to the variable.

E.g. :

void foo_by_value(int i) {
    // i is now stored in the int in the function's scope, it is not in any way affiliated with the variable or constant used to call the function
    
    i++; // This will only update the value of i inside this function
}

void foo_by_reference(int* i) {
    // i now holds the value of the memory address to an int. You are passing the pointer by value to obtain the variable by reference

    (*i)++; // This will update the value of the variable passed to the function
}

Hope that helped clear some stuff up!

0
0___________ On

You can also use macro for that

#define SWAP(type,x,y) do {type t_e_m_p___ = (x);(x) = (y); (y) = t_e_m_p___;} while(0)

int main(void)
{
    double d1 = 5.9,d2 = 7.4;
    SWAP(double, d1, d2);
    printf("Swapped: %f, %f\n", d1,d2);
}

No pointers needed