GfG QA is closing soon... Please refer PRACTICE or GfG now on wards !!

call by value/reference?????

func(char *s1,char * s2)
{
char *t;
t=s1;
s1=s2;
s2=t;
}
void main()
{
char *s1="jack", *s2="jill";
func(s1,s2);
printf("%s %s ",s1,s2);
}

 

 


what is OUTPUT?????

asked Aug 14, 2016 by Raminder Singh
if its call by reference then why the value of s1 and s2 in main function is not changing??

1 Answer

Output is 

jack jill 

It is call by reference. Arrays are always passed by reference due to memory constraints. Try this code for analysis. 

#include <stdio.h>
void func(char *s1,char * s2)
{
printf("\nINSIDE\n");
printf("S1 = %p ", s1);
printf("S2 = %p", s2);
char *t;
t=s1;
s1=s2;
s2=t;
printf("\n\n--------\n");
printf("S1 = %p : %s", s1, s1);
printf("\nS2 = %p : %s", s2, s2);

}

void main()
{
char *s1="jack", *s2="jill";
printf("S1 = %p", s1);
printf("S2 = %p", s2);
func(s1,s2);
printf("\n\nAFTER\n--------\n");
printf("S1 = %p", s1);
printf("S2 = %p", s2);

printf("\n%s %s ",s1,s2);
}

Here also references are being passed. But since there is no change in the values of the references, nothing happens. Point to note that the local variables of main function do change their references, while the local variables of the func do. 

answered Aug 14, 2016 by harshitgarg
...