Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
C#
#include<stdio.h>
void callbyvalue1(char a[],char b[])
{
char *x;
x=a;
a=b ;
b=x;
}
void callbyvalue2(char a[],char b[])
{
strcat(a,b);
}
void main()
{
char a[10],b[10];
scanf("%s%s",&a,&b);
callbyvalue1(a,b);
printf("%s\t%s",a,b);
callbyvalue2(a,b);
printf("%s\t%s",a,b);
}

Input:
a=hai
b=hello
what will be the output after callbyvalue1 and callbyvalue2

[This is the re-post of exact same question which was recently posted. I don't remember if it was the same inquirer or not, but the code samples are identical. At that time, the inquirer got a comprehensive answer. The page could have been deleted due to abuse reports; I'm not sure.

In all cases, this is either a re-post or the second question copied from the same source as the first one; some kind of abuse, anyway.

I reproduced my past answer, but it should not happen.

— SA]

Posted
Updated 23-Jul-13 5:40am
v3
Comments
[no name] 23-Jul-13 11:38am    
This looks strangely familiar and you could easily find out by simply running your code.
Sergey Alexandrovich Kryukov 23-Jul-13 11:41am    
Exactly. Please see my comment in the edited question and my answer. In all cases, this post is the abuse of the OP.
—SA
lewax00 23-Jul-13 12:03pm    
Does that even compile? I'm pretty sure when passing arrays as parameters you have to specify the size in the parameter list or use a pointer. [e.g. void callbyvalue1(char a[10],char b[10]) or void callbyvalue1(char *a, char *b)]
Sergey Alexandrovich Kryukov 23-Jul-13 12:54pm    
Yes, it will compile. And "strcat" will cause warning with recommendation to use safer "strcat_s". The implementation may infer the length assuming null terminator (I always thought it was a great lame), whatever. It only makes no sense.
—SA

1 solution

First of all, in C (not in C++), there are no references, and the parameter-passing mechanism is always by value.

In first case, you create a pointer x on stack and never use it, so the value of this pointer is discarded. It's less obvious with a and b. The values of these pointers (not objects referenced by them, but pointers) are copies on stack and modified. When you return to the caller, the modified values are discarded, because the stack frame is removed. After return to the called, these two pointers remain the same.

Did you want just to swap two objects? Then you would need to use pointers to pointers.

In second case, the function strcat returns a value, but you ignore the return. Please see: http://www.cplusplus.com/reference/cstring/strcat/[^].

You can get a warning recommending you to use strcat_s instead, as strcat is considered unsafe.

—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900