I'm new to C and still trying to grasp the concept of pointers. I know how to write a swap function that works...I'm more concerned as to why this particular one doesn't.
void swap(int* a, int* b)
{
int* temp = a;
a = b;
b = temp;
}
int main()
{
int x = 5, y = 10;
int *a = &x, *b = &y;
swap(a, b);
printf(“%d %d\n”), *a, *b);
}
The reason it didn't swap is because primitive variables are passed by value. This is what happens: Arguments are evaluated to values. Boxes for parameter variables are created.
swap() function in C++ Here is the syntax of swap() in C++ language, void swap(int variable_name1, int variable_name2); If we assign the values to variables or pass user-defined values, it will swap the values of variables but the value of variables will remain same at the actual place.
To answer your question directly, no there is no swap function in standard C, although it would be trivial to write.
C++ program:swap is used to swap two number using pointers. It takes two integer pointers as the arguments and swaps the values stored in the addresses pointed by these pointers.
Your swap()
function does work, after a fashion - it swaps the values of the variables a
and b
that are local to swap()
. Unfortunately, those are distinct from the a
and b
in main()
- so you don't actually see any effect from swapping them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With