0
Why swapping does not occurs
#include<stdio.h> int swap(int a,int b) { int temp; temp=a; a=b; b=temp; return(a,b); } int main() { int c=5,d=4; printf("after swap"); swap(c,d); printf("%d%d",c,d); return 0; }
3 odpowiedzi
+ 6
You can't return two numbers.
return(a,b);
Your return type is int then you must return only an int.
+ 3
1. Change the `swap` function signature to accept pointer type for parameters instead of `int`. The function doesn't need to return anything, because it directly modifies the given arguments. So change return type to `void`.
void swap(int* a, int* b)
2. Remove the `return` statement from `swap` function. A function with `void` return type should not return anything explicitly.
3. Inside `swap` function use dereference operator '*' to obtain and/or modify values of given arguments, <a> and <b>.
int temp = *a;
*a = *b;
*b = temp;
4. In main function, pass the address of the arguments instead of their value.
swap(&c, &d);
P.S. Please consider revising C lesson chapters related to pointers 👍
0
Ragul P, there is a concept of call by value and call by reference
Please go here for better understanding.
http://cs-fundamentals.com/tech-interview/c/difference-between-call-by-value-and-call-by-reference-in-c.php