Reputation: 7
So I'm new to programming. And I found this code from Quora when searching about different uses of void in C. I first assumed it would have a result of:
"Before swapping: 5, 10 After swapping: 10, 5"
But I get an output of:
"Before swapping: 5, 10 After swapping: 5, 10"
instead.
I felt like I needed to isolate either "swap(num1, num2);" "printf("After swapping: %d, %d \n", num1, num2);"
or
"int num1= 5, num2 = 10;"
from the rest of the statements inside the main function.
I tried declaring "int num1= 5, num2 = 10 ;" outside of main and also tried putting it inside of the swap function. That didn't work obv.
// The problem
void swap( int var1, int var2 )
{
int temp;
temp=var1;
var1=var2;
var2=temp;
}
void main( )
{
int num1= 5, num2 = 10;
printf("Before swapping: %d, %d \n", num1, num2);
swap(num1, num2);
printf("After swapping: %d, %d \n", num1, num2);
}
So, what are my options to have the desired output of:
"Before swapping: 5, 10 After swapping: 10, 5"
?
Upvotes: 0
Views: 91
Reputation: 538
You should pass in the addresses of num1 and num2 to the swap function
void swap(int *var1, int *var2)
{
int temp = 0;
temp = *var1;
*var1 = *var2;
*var2 = temp;
}
void main(void)
{
int num1= 5, num2 = 10;
printf("Before swapping: %d, %d \n", num1, num2);
swap(&num1, &num2);
printf("After swapping: %d, %d \n", num1, num2);
}
Upvotes: 2