I know that there is no Call by reference in C language. but, Some people say that there is a Call by reference in C. I'm confused.
As far as I know, when handing over the factor to the function in C, I know that the value transferred to the function is received by making a local copy as a parameter.
However, in C , "Call by reference" is possible because "the same element that differs only from the factor and name" is created by the reference "&". Is that true?
CodePudding user response:
I know that there is no Call by reference in C language.
Correct. C always passes by value.
Some people say that there is a Call by reference in C. I'm confused.
They are wrong. This is very easy to test.
Let's start by looking at this small Perl program.
use 5.014;
sub f {
$_[0] = 456; # $_[0] is the first argument.
}
my $x = 123;
f( $x );
say $x; # 456
Changing the parameter changed the argument. This is an example of pass by reference. Perl arguments are passed by reference.
Now let's do the same thing in C.
#include <stdio.h>
void f( int x ) {
x = 456;
}
int main( void ) {
int x = 123;
f( x );
printf( "%d\n", x ); // 123
}
Changing the parameter had no effect on the argument. This is an example of pass by value. C's arguments are passed by value.
You can use pointers to achieve a similar result.
#include <stdio.h>
void f( int *xp ) {
*xp = 456;
}
int main( void ) {
int x = 123;
f( &x );
printf( "%d\n", x ); // 456
}
Though note that the argument (the pointer) is still passed by value. Changing xp
itself (as opposed to *xp
) has no effect on the caller.
However, in C , "Call by reference" is possible
Correct.
C normally uses pass by value.
#include <iostream>
using namespace std;
void f( int x ) {
x = 456;
}
int main( void ) {
int x = 123;
f( x );
cout << x << endl; // 123
}
But pass by reference can be requested using &
.
#include <iostream>
using namespace std;
void f( int &x ) {
x = 456;
}
int main( void ) {
int x = 123;
f( x );
cout << x << endl; // 456
}
CodePudding user response:
C sometimes appears to pass by reference. The detail is that the argument goes through automatic conversions and that argument is passed by value. The effect is that the original augment appears to experience a pass-by-reference.
- When an argument is a function, it may look/act like it is pass by reference. Functions are converted to the address of a function. The function
sqrt
is not passed by value.foo()
receives the address of the function as a function pointer.
foo(sqrt);
- An array looks like it is passed by reference in that
bar()
does not receive the value of the array. What happened under the table is that the array is converted to the type and address of the first element andbar()
receives a pointer to achar
.bar()
may do things that changes[]
, exactly what pass by refence does in other languages, yet in C there is a technical under-the-table conversion that maintains the idea of pass only by value.
char s[1];
bar(s);