468,457 Members | 1,685 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,457 developers. It's quick & easy.

pass by reference in c----help banfa

39
Hi.Does C support pass by reference or only pass by value?If we pass the address of a variable and take it in the function definition with a pointer, then will it be pass by reference?Thanks for help.

Jerico
Oct 17 '06 #1
21 5417
vermarajeev
180 100+
Hi.Does C support pass by reference or only pass by value?If we pass the address of a variable and take it in the function definition with a pointer, then will it be pass by reference?Thanks for help.

Jerico
C supports both pass by reference and pass by value. In C, the corresponding parameter in the called function must be declared as a pointer type.

Here is a sample program

Expand|Select|Wrap|Line Numbers
  1. void swapInt(int *x, int* y)
  2. {
  3.     int temp = *x;
  4.     *x = *y;
  5.     *y = temp;
  6. }
  7. int main(int argc, char** argv[])
  8. {
  9.     int x =10, y = 20;
  10.     cout<<"Before swapping"<<endl;
  11.     cout<<"x:"<<x<<"\t"<<"y:"<<y<<endl;
  12.  
  13.     swapInt(&x, &y);
  14.  
  15.     cout<<"After swapping"<<endl;
  16.     cout<<"x:"<<x<<"\t"<<"y:"<<y<<endl;
  17.  
  18.     return 0;
  19. }
Oct 17 '06 #2
vermarajeev
180 100+
C supports both pass by reference and pass by value. In C, the corresponding parameter in the called function must be declared as a pointer type.

Here is a sample program

Expand|Select|Wrap|Line Numbers
  1. void swapInt(int *x, int* y)
  2. {
  3.     int temp = *x;
  4.     *x = *y;
  5.     *y = temp;
  6. }
  7. int main(int argc, char** argv[])
  8. {
  9.     int x =10, y = 20;
  10.     cout<<"Before swapping"<<endl;
  11.     cout<<"x:"<<x<<"\t"<<"y:"<<y<<endl;
  12.  
  13.     swapInt(&x, &y);
  14.  
  15.     cout<<"After swapping"<<endl;
  16.     cout<<"x:"<<x<<"\t"<<"y:"<<y<<endl;
  17.  
  18.     return 0;
  19. }
Hi I'm extremely sorry about my above comments,

C only passes parameters by value. That means, given a function call, it passes values over to the other function.

In the above code, We get C to simulate (SIMULATE!) pass-by-reference.

Thankx
Oct 17 '06 #3
vermarajeev
180 100+
In the above code, C is still passing by value, but now it is simulating pass-by-reference

I think, this is what you wanted???
Oct 17 '06 #4
Banfa
9,051 Expert Mod 8TB
In the above code, C is still passing by value, but now it is simulating pass-by-reference

I think, this is what you wanted???
I wouldn't have thought so, you seem to have managed to muddy your own explaination.

Pass by pointer normally is called pass by reference although I do understand why you say it is simulated I just not sure that is a distinction that needs making, not to mention in what way do you think a "non-simulated" method of passing by reference differs from the C method of passing a pointer?
Oct 17 '06 #5
vermarajeev
180 100+
I wouldn't have thought so, you seem to have managed to muddy your own explaination.

Pass by pointer normally is called pass by reference although I do understand why you say it is simulated I just not sure that is a distinction that needs making, not to mention in what way do you think a "non-simulated" method of passing by reference differs from the C method of passing a pointer?
Hi Banfa,
Thankx for your comments...
Please refer to this link for your explanation


http://www.maths.cam.ac.uk/undergrad/tripos/catam/ccatsl/manual/node50.html
Oct 17 '06 #6
Banfa
9,051 Expert Mod 8TB
Please refer to this link for your explanation

http://www.maths.cam.ac.uk/undergrad/tripos/catam/ccatsl/manual/node50.html
Strictly speaking that link does not explain anything, it just states the same point again with no explaination.

My point is that any language that "passes by reference" must pass something and the most logical thing is the memory location of the variable being passed, which is what a pointer is.

There is no functional difference between "simulated pass by reference" and "pass by reference" in what the machine is actually doing, in both cases it is likely that it is passing a pointer to the called function.
Oct 17 '06 #7
Banfa
9,051 Expert Mod 8TB
Oh and 1 final point, taken from that link

With the exception of arrays and functions (see below), C always passes arguments `by value': a copy of the value of each argument is passed to the function; the function cannot modify the actual argument passed to it:
This is incorrect or at least inconsistent with what the rest of the page is saying. You can't pass arrays or functions as parameters, you always pass pointers to arrays or pointers to functions. As with any other pointer these pointers are passed by value.

All you ever pass in C is a value but sometimes that value is a memory location of something else.
Oct 17 '06 #8
jerico
39
Thanks banfa.But can you explain how a pointer is passed by value?Please explain it with an example.

regards,
jerico
Oct 17 '06 #9
tyreld
144 100+
This is probably one of the most misunderstood aspects of C programming. There is a general lack of understanding of the actual formal semantic meaning of the different parameter passing types. The biggest mistake is the assumption that since pointers are a reference to something else that passing a pointer makes the call pass by reference. Passing semantics only refer to the parameter being passed. Entities pointed to by pointers must be explictly dereferenced whereas an entity passed by reference will be indirectly addressed under the covers.

When a paramater is passed by value the parameter in the callee contains a copy of the value from the callers parameter. These are 2 seperate objects. Changes made explicitly to the callee's parameter do not effect the callers.

When a parameter is passed by reference the parameter in the callee represents a view of the parameter from the caller. Any changes explicitly made to the callee's parameter directly changes the caller's parameter.

So, what does this mean?

From a formal perspective the C language only passes parameters using pass-by-value semantics. If you don't believe me go try and argure for pass-by-reference on comp.lang.c, or for you University students answer C is pass-by-reference on your next Programming Language Theory exam and see what happens.

There is no pass-by-reference in C. Pointers are passed by value. The callee has a copy of the address that was in the callers pointer. The pointer is the parameter being passed not the enitity that the pointer points to.

QED
Oct 17 '06 #10
tyreld
144 100+
Everything in C is passed by value. This means pointers as well. With this in mind lets not forget what the value of a pointer is. The value of a pointer is simply the memory address where we have stored something else (ie. an int value, or a float value, or even a pointer to something else).

Now an example.

Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2.  
  3. void foo(int *f_ptr)
  4. {
  5.    int x = 10;
  6.    f_ptr = &x;
  7. }
  8.  
  9. void bar(int *b_ptr)
  10. {
  11.    *b_ptr = 10;
  12. }
  13.  
  14. int main(void)
  15. {
  16.    int  v;           // an integer
  17.    int *ptr;         // a pointer to an integer
  18.  
  19.    v = 5;         // v is now an integer with the value 5
  20.    ptr = &v;      // ptr now contains the address where we can find the value of v
  21.    // Pass the address in ptr to foo
  22.    foo(ptr);
  23.  
  24.    printf("The value of v = %d\n", v);
  25.  
  26.  
  27.    bar(ptr);
  28.  
  29.    printf("The value of v = %d\n", v);
  30.  
  31.    return 0;
  32. }
  33.  
Oct 17 '06 #11
vermarajeev
180 100+
Hi,
Why I stated SIMULATED! in my previous post, here is the reason...

Just consider this example
Expand|Select|Wrap|Line Numbers
  1. int main()
  2.  {
  3.      int a,b;
  4.     a=5;
  5.     b = 7;
  6.     foo(&a, &b);
  7.     printf("%d %d\n", a,b);
  8.  }
  9.  
  10.  void foo(int *x, int *y)
  11.  {
  12.     *x = 6;
  13.     *y = 8;
  14.  }
You see the first question to ask .. is what values are passed over from the function call to foo? It is &a and &b, which are addresses of a and b respectively. Thus x contains the address of variable a. And y contains the address of variable b.

Since *x is the deference operator, we can say that instead of referring to x, *x is referring to a, thus effectively assigning 6 to a and the same for *y=8. C is still passing by value, but now it is simulating pass-by-reference. Because these pointers variables being passed in as arguments into foo helps foo to indrectly refer to a and b which are local variables in another function.

So, is the reason for my comments above....

Thankx
Oct 18 '06 #12
tyreld
144 100+
Hi,
Why I stated SIMULATED! in my previous post, here is the reason...

Just consider this example
Expand|Select|Wrap|Line Numbers
  1. int main()
  2.  {
  3.      int a,b;
  4.     a=5;
  5.     b = 7;
  6.     foo(&a, &b);
  7.     printf("%d %d\n", a,b);
  8.  }
  9.  
  10.  void foo(int *x, int *y)
  11.  {
  12.     *x = 6;
  13.     *y = 8;
  14.  }
You see the first question to ask .. is what values are passed over from the function call to foo? It is &a and &b, which are addresses of a and b respectively. Thus x contains the address of variable a. And y contains the address of variable b.

Since *x is the deference operator, we can say that instead of referring to x, *x is referring to a, thus effectively assigning 6 to a and the same for *y=8. C is still passing by value, but now it is simulating pass-by-reference. Because these pointers variables being passed in as arguments into foo helps foo to indrectly refer to a and b which are local variables in another function.

So, is the reason for my comments above....

Thankx
I know you said simulated, and I know of many poorly worded examples on the internet that I suspect you conjured this example from. This simulates nothing. You are explicitly passing addresses (&a must be evaluated before the function call can take place since the address must be copied into the stack value for x) and then dereferencing them in the callee. This is nothing more then short cutting. I will also point out in formal language semantics an expression can never be passed as a reference.

A simulation should imitate the internal processes and not merely the results of the thing being simulated. If you want to simulate pass by reference in C write a C interpreter with call by reference semantics. All you've managed to illustrate is the use of memory addresses in C for indirect addressing of data. References are a language abstraction that allow you to seemlessly operate on the same entity. Memory addresses are nothing more then a value. All beit a value that allows you to dereference something.

It is the continual poliferation of this example that leads to confusion. Especially, when C programmers make the leap to C++ and discover the poorly chosen reference operator, and attempt the following because they misunderstand the concept of an address value and a reference.

Expand|Select|Wrap|Line Numbers
  1. void foo(int &not_a_ptr) {
  2.    not_a_ptr = 10;
  3. }
  4.  
  5. int main(void) {
  6.    int a = 5;
  7.  
  8.    foo(&a);   // WRONG
  9.  
  10.    return 0;
  11. }
  12.  
Oct 18 '06 #13
vermarajeev
180 100+
Ok, I think I shouldnt have conjured this example....Fine!!!!

But I still have one doubt in this statement

But as per pass by value funda, a copy of the parameter is created...But in the above example,
when we say
int main()
{
swap(&a, &b);
}
swap(int* x, int* y)
{

}

How is that the C language only passes parameters using pass-by-value semantics????

Thankx
Oct 18 '06 #14
jerico
39
stope talking these craps.
Oct 18 '06 #15
tyreld
144 100+
The value of a pointer is an address. The expression "&a" evaluates to a value which is an address. So, in your example: at runtime the values of "&a" and "&b" are first evaluated before being passed to the function. The address values are then copied into the pointers "x" and "y" in the stack frame allocated for the "swap" function. The pass by semantics have to do with the underlying behavior. Not with the fact that C provides pointers that allow us to do indirect addressing.
Oct 18 '06 #16
Banfa
9,051 Expert Mod 8TB
stope talking these craps.
Actually this is quite an important and topical discussion, if you care to listen you may learn something.

The answer to your question is that C only passes parameters by value. However the value of those parameters passed may in fact be the memory location of a variable external to a function allowing the function to alter the value of that external variable.


The mistake I made centres around this statement by tyreld

"Passing semantics only refer to the parameter being passed."

and my tendancy to think at machine level.

I am (more or less) correct that at machine level there is no such thing as pass by reference, there is only pass by value although that value may be the memory location of another variable.

"pass by reference" and "pass by value" are only applicable at the language level because even if a language "passes by reference" it is likely that once this is translated to machine level this results in a pass by value of a memory location.

As such C passes by value, this should not be a surprise because C is and always has been only 1 step away from assembler (the machine level). In fact I believe C was designed to have easy and in many cases direct translation from C syntax to assembler/machine code.

Higher level languages with more abstraction from the machine (VB, Java) may or may not pass by reference (VB does by default I believe). This is part of the language semantics, i.e. how the language works as viewed by the user, not how it works on the machine.

Whatever the case it is imperitive that you know and understand the passing semantics for the language you are using.
Oct 18 '06 #17
jerico
39
I was only referring to the posts of vermarajeev.Not others.I hav posted here to learn something , not for fun.Anyway thanks for reply.

jerico
Oct 19 '06 #18
vermarajeev
180 100+
I was only referring to the posts of vermarajeev.Not others.I hav posted here to learn something , not for fun.Anyway thanks for reply.

jerico
Hey man!!
What do you mean talking that way?????
Who is doing fun out here????
Oct 19 '06 #19
Banfa
9,051 Expert Mod 8TB
I was only referring to the posts of vermarajeev.Not others.I hav posted here to learn something , not for fun.Anyway thanks for reply.

jerico
Hey man!!
What do you mean talking that way?????
Who is doing fun out here????
Stop bickering or I'll send you both to bed without supper :)

May be you did start this thread jerico but it you look at the post vermarajeev made that you have complained at it ended with a big question .

vermarajeev is clearly not entirely clear on the subject and, given that this is a public forum, has every right to join in the conversation and ask what ever question or give whatever example they feel they need to in order to clarify the situation as long as it is on topic for the thread.


If you think you understand something then attempting to explain it to someone else is a fine way of concreating it in your brain and if you know that there are other knowledgible people listening also a good way of making sure you have things correct since if you are wrong you will probably be corrected.

Have you not heard the phase "see one, do one, teach one", as borrowed from the medical profession.
Oct 19 '06 #20
vermarajeev
180 100+
Stop bickering or I'll send you both to bed without supper :)

May be you did start this thread jerico but it you look at the post vermarajeev made that you have complained at it ended with a big question .

vermarajeev is clearly not entirely clear on the subject and, given that this is a public forum, has every right to join in the conversation and ask what ever question or give whatever example they feel they need to in order to clarify the situation as long as it is on topic for the thread.


If you think you understand something then attempting to explain it to someone else is a fine way of concreating it in your brain and if you know that there are other knowledgible people listening also a good way of making sure you have things correct since if you are wrong you will probably be corrected.

Have you not heard the phase "see one, do one, teach one", as borrowed from the medical profession.
Hi banfa,
thankx for your suggestion,

Jerico, sorry, if I have discommode you
Thankx
Oct 19 '06 #21
jerico
39
no offence meant..take my olive branch..jerico
Oct 21 '06 #22

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

4 posts views Thread by Amr Mostafa | last post: by
4 posts views Thread by Omar Llanos | last post: by
4 posts views Thread by z_learning_tester | last post: by
7 posts views Thread by John | last post: by
9 posts views Thread by Edward Diener | last post: by
4 posts views Thread by Jon Slaughter | last post: by
3 posts views Thread by Prabu Ramasamy | last post: by
15 posts views Thread by J. Peng | last post: by
1 post views Thread by subhajit12345 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.