Close
Close

why the first code can swap the two numbers while the second code can not swap the two numbers

   mohit19699soni

#include <stdio.h>
void swap( int *a, int *b )
{
    int t; 
    t = *a; 
    *a = *b; 
    *b = t; 
}
int main() 
{
    int num1, num2; 
    printf("Enter first number\n");
    scanf("%d", &num1);
    printf("Enter second number\n");
    scanf("%d", &num2);
    swap( &num1, &num2);
    printf("First number : %d\n", num1);
    printf("Second number : %d\n", num2);
    return 0;
}

 

 

 

v

#include <stdio.h>
void swap( int *a, int *b )
{
    int t; 
    t = *a; 
    *a = *b; 
    *b = t; 
}
int main() 
{
    int num1, num2; 
    printf("Enter first number\n");
    scanf("%d", &num1);
    printf("Enter second number\n");
    scanf("%d", &num2);
    swap( &num1, &num2);
    printf("First number : %d\n", num1);
    printf("Second number : %d\n", num2);
    return 0;
}
#include <stdio.h>
void swap( int a, int b )
{
    int t; 
    t = a; 
    a =b; 
    b =t; 
}
int main() 
{
    int num1, num2; 
    printf("Enter first number\n");
    scanf("%d", &num1);
    printf("Enter second number\n");
    scanf("%d", &num2);
    swap(num1,num2);
    printf("First number : %d\n", num1);
    printf("Second number : %d\n", num2);
    return 0;
}


Answers

  •   

    When you pass pointers to a function, you pass the address to the function. So, the function can access the real variables and thus can change them.

    But when you pass the value instead of the function, a copies of the variables are passed instead of the real variables. So, making changes will only change the copies and not the real variables.



Ask Yours
Post Yours
Write your answer