Related
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?
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
}
Note that the argument (the pointer) is still passed by value. Changing xp itself (as opposed to *xp) has no effect on the caller.
Same goes for arrays. The degenerate into a pointer which is passed by value.
#include <stdio.h>
void f( char a[] ) {
a = "def";
}
int main( void ) {
char a[] = "abc";
f( a );
printf( "%s\n", a ); // abc
}
This could be called passing a reference. It is not passing by reference, however.
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
}
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.
Your confusion is, I'm afraid, inevitable, but it's not your fault.
People have been arguing about this question for a long time. (There's an FAQ list entry on the question that dates to the 1990's.) I didn't realize it was still a matter of debate, but evidently it is, because the same confusion you've experienced has been repeated (which is to say, validated) in the answers posted right here on this Stack Overflow question, where you hoped you'd get a definitive answer.
Depending on how you define your terms, all of the following statements are more or less true:
C does not have pass by reference. C always passes arguments by value.
C lets you simulate pass by reference, by passing a pointer instead. But the pointer is passed by value.
Arrays in C are passed by reference, because the array reference in the function call decays into a pointer to the array's first element. (But the pointer is passed by value.)
C++ has reference parameters, meaning that the programmer doesn't have to explicitly use the & operator in the call, or the * operator in the function. (But the implementation of that reference involves something very much like a pointer which is, again, passed by value.)
Or, in other words, for a sufficiently formal and restrictive definition of the term "pass by reference", C does not have it. But it has a couple of things that are pretty close, perhaps close enough to satisfy a less-formal definition, or to let you say, "You can get something a lot like call-by-reference in C, if you want."
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 argument experiences 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 and bar() receives a pointer to a char. bar() may do things that change s[], 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);
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.
The traditional definition of "pass by reference" is an aspect of subprogram calling semantics providing that the subprogram's parameters are bound to the same objects that are designated by the caller as the corresponding subprogram arguments.1,2 This has the effect that if the subprogram modifies the object identified by one of its parameters, including by assignment, then the caller can observe that modification (provided that the caller retains a way to examine that object). This is the typical implementation of Fortran's call semantics, among others.
For example, consider a program of this form (expressed in a polyglot pseudocode):
subprogram sub1(x)
x = 0
end
integer a
a = 42
call sub1(a)
print(a)
In a language with pass-by-reference semantics, the assignment to x in sub1 will modify the value of a in the caller, with the result that the program prints "0".
Pass-by-value is the main alternative: the names of subprogram parameters are not bound to the objects specified by the caller. They are instead bound to different objects with (initially) the same values as those presented by the caller. In a language with pass-by-value semantics, a program such as the above would be expected to print "42", as the subprogram's parameter x refers to a different object than the caller's a, therefore the subprogram's assignment to x is not visible to the caller.
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.
Yes, this is mandated by the C language specification:
An argument may be an expression of any complete object type. In
preparing for the call to a function, the arguments are evaluated, and
each parameter is assigned the value of the corresponding argument.
(C17 6.5.2.2/4; emphasis added)
As judged via the definitions above, this is unequivocally pass-by-value in all cases. However, there are a couple of cases that require special attention in this context:
One can pass the address of an object to a function -- for example, by means of the unary & operator. In that case, the function can modify the pointed-to object via the pointer it receives. Some people are inclined to characterize this as pass-by-reference, but it does not satisfy the definition above, because the argument was never the pointed-to object in the first place. Moreover, assignment to the received pointer itself does not modify the argument presented by the caller or the object to which it points.
The arguments presented by the caller are the results of evaluating the expressions presented, and C has some cases where the effect of that may be surprising to the uninitiated, especially
functions. Wherever the name of a function appears in a valid expression that is evaluated, it is automatically converted to a pointer.3 In particular, when the name of a function appears in the argument list of a function call, the corresponding parameter receives a pointer to the function. The called function can use that pointer to call the function it points to, even if that function's identifier is not in scope. But the function has not been passed by reference (by the above definition), for if the called function assigns a new value to the parameter, that does not modify the function it originally pointed to (nor the caller's copy of the function pointer, if it retains one).
arrays. C specifies that with only a few, narrow exceptions, expressions of array type are automatically converted to pointers. I think it's fair and consistent to describe that as the result of evaluating a (sub)expression of array type being a pointer to the first element of the array. The argument lists to function calls are no exception, so when you specify an array as a function argument, the corresponding function parameter receives a pointer to the first array element.
As a result, the called function can modify the array's elements via the pointer it receives. Some people describe that effect as the array having been passed by reference, but it doesn't actually satisfy the above definition. The parameter doesn't even have the same type as the caller's array, and moreover, if you assign a new value to the parameter itself then the effect is visible only in the function. In this sense, modifying array elements via a pointer received as a parameter is analogous to calling a function via a function pointer received 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?
Yes, one of the things that C++ has that C does not is references, and one of the major uses of references is providing pass-by-reference semantics that satisfy the above definition. It's not quite pass-by-reference in the Fortran sense because the parameter has a different type than the corresponding argument, but for most purposes, the parameter can be used in the same ways, and with the same effects, as the argument to which it is bound. In particular, assignment to a reference does affect the referenced object.
C++ references have some additional properties that differentiate them from pointers, among them:
A reference can be created only from another, valid object, either as a reference to that object or, if that object is itself a reference, as a copy of that reference (referring to the same object).
References cannot be rebound to different objects.
These play well with using C++ references for pass-by-reference.
Until now I have grounded my discussion in the definition given above, but it will be clear from the answers and comments given that there is a controversy here over whether that remains an appropriate definition. Some claim that the language has moved on, and in particular that in the context of C, the term "pass by reference" has become accepted as including passing a pointer. To be sure, some do use the term that way. On the other hand, "accepted" is clearly too strong a term, because plenty of others, including some voicing their opinions here, insist that it is is imprecise, sloppy, or simply wrong to describe passing a pointer to an object as passing that object by reference.
One thing to consider here is that the conventional meaning of these terms in context of most programming languages other than C has not appreciably moved from the traditional ones, even for much younger languages. C++ in particular is relevant because of the shared history and strong interoperability of these, and no C++ programmer would characterize passing a pointer as pass by reference. But the terminology is also well established in Java, which has only pass by value, including passing references by value, but not pass by reference. It also comes up in Python, which is like Java but more so, because all argument passing there is passing references by value. The distinction is important for explaining the semantics of those languages, as indeed it is for C, too.
Therefore, at present, if
you are engaging in comparative analysis of computer languages,
you want to express your ideas with maximum precision, or
you want to avoid, in many cases, earning a point of disrespect from a portion of your audience
then you will avoid conflating passing pointers with pass by reference. But if you do conflate the two then you can reasonably expect to be understood, at least in C-specific context.
1 Wikipedia definition
2 Strongly supported Stack Overflow definition
3 Including in their most common context, function calls: "The expression that denotes the called function shall have type pointer to function" (C17 6.5.2.2/1).
But, Some people say that there is a Call by reference in C. I'm confused.
This depends on how you define the term "call by reference":
Three years ago, I worked for a company in the automotive industry:
Pointer arguments that were pointing to a (single) variable (and not to an array) of the type someType were neither defined as "arguments of the type someType *" nor as "pointers to a someType" but as "'call by reference' arguments of the type someType".
You could also see this at the "[out]" or "[inout]" tag in the doxygen comments:
/*! \brief Example function (non-AUTOSAR)
* \param[in] foo Value of the "foo" force
* \param[out] bar Value of the "bar" speed
* \param[inout] foobar Current value of the "foobar" state
* \return True if calculating "bar" succeeded */
bool someFunction(someType foo, someType * bar, someType * foobar)
{
...
}
Microsoft's documentation of the Windows API seems to see this in a similar way - for example here:
BOOL GetExitCodeProcess(
[in] HANDLE hProcess,
[out] LPDWORD lpExitCode
);
“Pass by reference”1 is an old computer programming phrase that antedates the “reference” feature built into C++. It means providing a pointer to an object. The C standard says a pointer “provides a reference” (C 2018 6.2.5 20). References can be provided either manually by a programmer writing some explicit notation or by a feature built into a programming language.
When C++ developers named a new feature a “reference,” that did not change the prior usage of the term. When discussing “passing by reference” in languages other than C++ or others that provide built-in references, the phrase has its classic meaning.
C supports passing by reference (manually) but does not provide it as a built-in feature, except to the extent that arrays and functions undergo automatic conversions and adjustments that effect passing by reference. Programmers understand from context that “pass by reference” refers to passing a pointer in C and passing a built-in reference type in C++.
Footnote
1 The question uses the phrase “call by reference,” but this is an imprecise use of terminology. Whether we are discussing C++ or C, the issue is how arguments are passed, not how functions are called.
In C, all function arguments are passed by value, meaning each argument expression in the function call is fully evaluated and the result of that evaluation is passed to the function:
#include <stdio.h>
void swap( int a, int b )
{
int tmp = a;
a = b;
b = tmp;
}
int main( void )
{
int x = 10, y = 10;
printf( "Before swap: x = %d, y = %d\n" );
swap( x, y );
printf( " After swap: x = %d, y = %d\n" );
return 0;
}
The formal parameters a and b in the definition of swap are different objects in memory from the actual parameters x and y in main. The expressions x and y are fully evaluated, and the results of those evaluations (the values 10 and 20) are copied to a and b. Changing the values of a and b has no effect on x or y, and the output of the program will be
Before swap: x = 10, y = 20
After swap: x = 10, y = 20
We can fake pass-by-reference semantics by passing pointer values:
#include <stdio.h>
void swap( int *a, int *b )
{
int tmp = *a;
*a = *b;
*b = tmp;
}
int main( void )
{
int x = 10, y = 10;
printf( "Before swap: x = %d, y = %d\n" );
swap( &x, &y );
printf( " After swap: x = %d, y = %d\n" );
return 0;
}
Instead of passing the values of x and y, we're passing the results of the expressions &x and &y, which evaluate to the addresses of x and y.
a and b are still separate objects in memory from x and y, but instead of receiving the values of x (10) and y (20), they receive the addresses of x and y.
The expressions *a and *b can kinda-sorta be thought of as aliases for x and y, such that writing a new value to *a is the same as writing a new value to x and writing a new value to *b is the same as writing a new value to y. But this is not true pass-by-reference - it's passing pointers by value and manually dereferencing the pointers. The output of this program will be
Before swap: x = 10, y = 20
After swap: x = 20, y = 10
Switching to C++:
#include <iostream>
void swap( int &a, int &b )
{
int tmp = a;
a = b;
b = tmp;
}
int main( void )
{
int x = 10, y = 20;
std::cout << "Before swap: x = " << x << ", y = " << y << std::endl;
swap( x, y );
std::cout << " After swap: x = " << x << ", y = " << y << std::endl;
return 0;
}
The parameter declarations int &a and int &b declare a and b as references - a and b are not separate objects in memory, but rather they are alternate names or aliases for the objects designated by x and y1. You do not need to explicitly dereference a or b in the C++ code the way you have to in the C code. Like the second C example, the output will be:
Before swap: x = 10, y = 20
After swap: x = 20, y = 10
Logically speaking, anyway - the compiler may be using pointers under the hood to accomplish this, but that's hidden from you. As far as the behavior of the code is concerned, a and b are not independent objects from x and y.
In my University's C programming class, the professor and subsequent book written by her uses the term call or pass by reference when referring to pointers in C.
An example of what is considered a 'call by reference function' by my professor:
int sum(int *a, int *b);
An example of what is considered a 'call by value function' by my professor:
int sum(int a, int b);
I've read C doesn't support call by reference. To my understanding, pointers pass by value.
Basically, is it incorrect to say pointers are C's way of passing by reference? Would it be more correct to say you cannot pass by reference in C but can use pointers as an alternative?
Update 11/11/15
From the way my question originated, I believe a debate of terminology has stemmed and in fact I'm seeing two specific distinctions.
pass-by-reference (the term used mainly today): The specific term as used in languages like C++
pass-by-reference (the term used by my professor as a paradigm to explain pointers): The general term used before languages like C++ were developed and thus before the term was rewritten
After reading #Haris' updated answer it makes sense why this isn't so black and white.
you cannot pass by reference in C but can use pointers as an alternative
Yup, thats correct.
To elaborate a little more. Whatever you pass as an argument to c functions, it is passed by values only. Whether it be a variable's value or the variable address.
What makes the difference is what you are sending.
When we pass-by-value we are passing the value of the variable to a function. When we pass-by-reference we are passing an alias of the variable to a function. C can pass a pointer into a function but that is still pass-by-value. It is copying the value of the pointer, the address, into the function.
If you are sending the value of a variable, then only the value will be received by the function, and changing that won't effect the original value.
If you are sending the address of a variable, then also only the value(the address in this case) is sent, but since you have the address of a variable it can be used to change the original value.
As an example, we can see some C++ code to understand the real difference between call-by-value and call-by-reference. Taken from this website.
// Program to sort two numbers using call by reference.
// Smallest number is output first.
#include <iostream>
using namespace std;
// Function prototype for call by reference
void swap(float &x, float &y);
int main()
{
float a, b;
cout << "Enter 2 numbers: " << endl;
cin >> a >> b;
if(a>b)
swap(a,b); // This looks just like a call-by-value, but in fact
// it's a call by reference (because of the "&" in the
// function prototype
// Variable a contains value of smallest number
cout << "Sorted numbers: ";
cout << a << " " << b << endl;
return 0;
}
// A function definition for call by reference
// The variables x and y will have their values changed.
void swap(float &x, float &y)
// Swaps x and y data of calling function
{
float temp;
temp = x;
x = y;
y = temp;
}
In this C++ example, reference variable(which is not present in C) is being used. To quote this website,
"A reference is an alias, or an alternate name to an existing variable...",
and
"The main use of references is acting as function formal parameters to support pass-by-reference..."
This is different then the use of pointers as function parameters because,
"A pointer variable (or pointer in short) is basically the same as the other variables, which can store a piece of data. Unlike normal variable which stores a value (such as an int, a double, a char), a pointer stores a memory address."
So, essentially when one is sending address and receiving through pointers, one is sending the value only, but when one is sending/receiving a reference variable, one is sending an alias, or a reference.
**UPDATE : 11 November, 2015**
There has been a long debate in the C Chatroom, and after reading comments and answers to this question, i have realized that there can be another way to look at this question, another perspective that is.
Lets look at some simple C code
int i;
int *p = &i;
*p = 123;
In this scenario, one can use the terminology that, p's value is a reference to i. So, if that is the case, then if we send the same pointer (int* p) to a function, one can argue that, since i's reference is sent to the function, and thus this can be called pass-by-reference.
So, its a matter of terminology and way of looking at the scenario.
I would not completely disagree with that argument. But for a person who completely follows the book and rules, this would be wrong.
NOTE: Update inspired by this chat.
Reference is an overloaded term here; in general, a reference is simply a way to refer to something. A pointer refers to the object pointed to, and passing (by value) a pointer to an object is the standard way to pass by reference in C.
C++ introduced reference types as a better way to express references, and introduces an ambiguity into technical English, since we may now use the term "pass by reference" to refer to using reference types to pass an object by reference.
In a C++ context, the former use is, IMO, deprecated. However, I believe the former use is common in other contexts (e.g. pure C) where there is no ambiguity.
Does C even have ``pass by reference''?
Not really.
Strictly speaking, C always uses pass by value. You can simulate pass by reference yourself, by defining functions which accept pointers and then using the & operator when calling, and the compiler will essentially simulate it for you when you pass an array to a function (by passing a pointer instead, see question 6.4 et al.).
Another way of looking at it is that if an parameter has type, say, int * then an integer is being passed by reference and a pointer to an integer is being passed by value.
Fundamentally, C has nothing truly equivalent to formal pass by reference or c++ reference parameters.
To demonstrate that pointers are passed by value, let's consider an example of number swapping using pointers.
int main(void)
{
int num1 = 5;
int num2 = 10;
int *pnum1 = &num1;
int *pnum2 = &num2;
int ptemp;
printf("Before swap, *Pnum1 = %d and *pnum2 = %d\n", *pnum1, *pnum2);
temp = pnum1;
pnum1 = pnum2;
pnum2 = ptemp;
printf("After swap, *Pnum1 = %d and *pnum2 = %d\n", *pnum1, *pnum2);
}
Instead of swapping numbers pointers are swapped. Now make a function for the same
void swap(int *pnum1, int *pnum2)
{
int *ptemp = pnum1;
pnum1 = pnum2;
pnum2 = temp;
}
int main(void)
{
int num1 = 5;
int num2 = 10;
int *pnum1 = &num1;
int *pnum2 = &num2;
printf("Before swap, *pnum1 = %d and *pnum2 = %d\n", *pnum1, *pnum2);
swap(pnum1, pnum2);
printf("After swap, *pnum1 = %d and *pnum2 = %d\n", *pnum1, *pnum2);
}
Boom! No swapping!
Some tutorials mention pointer reference as call by reference which is misleading. See the this answer for the difference between passing by reference and passing by value.
From the C99 standard (emphasis mine):
6.2.5 Types
20 Any number of derived types can be constructed from the object and function types, as
follows:
...
— A pointer type may be derived from a function type or an object type, called the referenced type. A pointer type describes an object whose value provides a reference to an entity of the referenced type. A pointer type derived from the referenced type T is sometimes called ‘‘pointer to T’’. The construction of a pointer type from a referenced type is called ‘‘pointer type derivation’’. A pointer type is a complete object type.
Based on the above, what your professor said makes sense and is correct.
A pointer is passed by value to functions. If the pointer points to a valid entity, its value provides a reference to an entity.
"Passing by reference" is a concept. Yes, you are passing the value of a pointer to the function, but in that instance the value of that pointer is being used to reference the variable.
Someone else used a screwdriver analogy to explain that it is wrong to refer to the passing of pointers as passing by reference, saying that you can screw a screw with a coin but that that doesn't mean you would call the coin a screw driver. I would say that is a great analogy, but they come to the wrong conclusion. In fact, while you wouldn't claim a coin was a screwdriver, you would still say that you screwed the screw in with it. i.e. even though pointers are not the same as c++ references, what you are using them to do IS passing by reference.
C passes arguments by value, period. However, pointers are a mechanism that can be used for effectively passing arguments by reference. Just like a coin can be used effectively as a screw driver if you got the right kind of screw: some screws slit are even chosen to operate well with coins. They still don't turn the coins into actual screw drivers.
C++ still passes arguments by value. C++ references are quite more limited than pointers (though having more implicit conversions) and cannot become part of data structures, and their use looks a lot more like the usual call-by-reference code would look, but their semantics, while very much catered to match the needs of call-by-reference parameters, are still more tangible than that of pure call-by-reference implementations like Fortran parameters or Pascal var parameters and you can use references perfectly well outside of function call contexts.
Your professor is right.
By value , it is copied.
By reference, it is not copied, the reference says where it is.
By value , you pass an int to a function , it is copied , changes to the copy does not affect the original.
By reference , pass same int as pointer , it is not copied , you are modifying the original.
By reference , an array is always by reference , you could have one billion items in your array , it is faster to just say where it is , you are modifying the original.
In languages which support pass-by-reference, there exists a means by which a function can be given something that can be used to identify a variable know to the caller until the called function returns, but which can only be stored in places that won't exist after that. Consequently, the caller can know that anything that will be done with a variable as a result of passing some function a reference to it will have been done by the time the function returns.
Compare the C and C# programs:
// C // C#
int x=0; int x=0;
foo(&x); foo(ref x);
x++; x++;
bar(); bar();
x++; x++;
boz(x); boz(x);
The C compiler has no way of knowing whether "bar" might change x, because
foo() received an unrestricted pointer to it. By contrast, the C# compiler
knows that bar() can't possibly change x, since foo() only receives a
temporary reference (called a "byref" in .NET terminology) to it and there
is no way for any copy of that byref to survive past the point where foo()
returns.
Passing pointers to things allows code to do the same things that can be done with pass-by-ref semantics, but pass-by-ref semantics make it possible for code to offer stronger guarantees about things it won't do.
To demonstrate, here is an example code recreating the instance of passing a dynamically allocated array to a function.
#include <stdio.h>
#include <stdlib.h>
void fx1(int* arr) {/* code here */ }
int main() {
int *arr = (int *) malloc(sizeof(int) * 10);
fx1(arr);
free(arr);
return 0;
}
In the example, I first create a dynamically allocated array, arr. Then, I pass it to a function called fx1.
The title is exactly my question. Is passing a dynamically allocated array to a function in C an instance of pass-by-value or pass-by-reference? I would also like a reference/s (book, documentation, etc) if you have an answer for this.
In C, everything is passed by value. In your concrete example arr is. You don't have references like in C++ or Java.
Let's take a C++ example:
void foo(int& i) {
++i;
}
int main() {
int i = 1;
foo();
}
Here, true references are used. i is passed by reference and foo modifies i over a reference to i. No "copying by value" takes place.
OTOH, in C, you don't have references. You can only write something like
void foo(int* i) {
++*i;
}
int main() {
int i = 1;
foo(&i);
}
To pass something "by reference"1 in C, you need to pass a pointer to it, just like you did. The pointer itsself is passed by value but it refers to a memory area (here i) modifiable by both the function and the allocator.
In the end, if you want to pass something "by reference" in C, copying by value is always involved. Not so in C++.
Quoting from K&R, 1.8 Arguments - Call by Value:
In C, all function arguments are passed by value.''
1 Note that this is within double quotes. C doesn't have "pass-by-reference." Period.
It is "both":
The pointer is passed by value, the array "by reference".
C Standard draft, N1256:
6.5.2.2 Function calls
...
4 An argument may be an expression of any object type. In preparing for the call to a function, the arguments
are evaluated, and each parameter is assigned the value of the
corresponding argument.
...
I put "both" and "by reference" in quotes, because there are no references in C. A pointer is not a reference, but when used to "pass an array" to a function, it is roughly comparable, in the sense that if the function modifies the array, the changes are visible to the caller. I think this helps understanding what happens here.
We say that an array decays to a pointer, when passed to a function. "Decay" because the pointer looses some information, namely the length of the array. So saying this is similar to "pass by reference" is meant only from an application point of view.
This question already has answers here:
What's the difference between passing by reference vs. passing by value?
(18 answers)
Closed 8 years ago.
What is the difference between passing by reference the parameters in a function and passing pointer variables as a parameter in a function ?
There is no pass by reference in C, it's always pass by value.
C developers can emulate pass by reference, by passing the pointers to a variable and the accessing it using dereferencing within the function. Something like the following, which sets a variable to 42:
static void changeTo42 (int *pXyzzy) {
*pXyzzy = 42;
}
:
int x = 0;
changeTo42 (&x);
Contrast that with the C++ true pass by reference, where you don't have to muck about with pointers (and especially pointers to pointers, where even seasoned coders may still occasionally curse and gnash their teeth):
static void changeTo42 (int &xyzzy) {
xyzzy = 42;
}
:
int x = 0;
changeTo42 (x);
I would implore ISO to consider adding true references to the next C standard. Not necessarily the full capability found in C++, just something that would fix all the problems people have when calling functions.
You might be thinking of C++. I'll cover that below.
In C there is no passing by reference. To accomplish the same feat, you can send a pointer to a variable as an argument and dereference the pointer in the method, as shown in paxdiablo's comment.
In C++, you could accomplish the same thing if you tried to pass by reference C-style (as explained previously) or if you tried passing the arguments as such:
static void multiply(int& x){
x * 7;
}
void main(){
int x = 4;
multiply(x);
}
The variable x at the end of this program would equal 28.
Does C have references? i.e. as in C++ :
void foo(int &i)
No, it doesn't. It has pointers, but they're not quite the same thing.
In particular, all arguments in C are passed by value, rather than pass-by-reference being available as in C++. Of course, you can sort of simulate pass-by-reference via pointers:
void foo(int *x)
{
*x = 10;
}
...
int y = 0;
foo(&y); // Pass the pointer by value
// The value of y is now 10
For more details about the differences between pointers and references, see this SO question. (And please don't ask me, as I'm not a C or C++ programmer :)
Conceptually, C has references, since pointers reference other objects.
Syntactically, C does not have references as C++ does.