Thread: call by reference and a call by value

  1. #1
    Registered User
    Join Date
    Sep 2001
    Posts
    3

    Unhappy call by reference and a call by value

    Can anyone explain me the diffrence between call by reference and a call by value

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    see for yourself.... compile and run this:-
    Code:
    #include <stdio.h>
    #include<stdlib.h>
    void byvalue (int x)
    {
    x+=5; // x=x+5
    printf("Value of x in byvalue is %d\n",x);
    }
    
    void byref(int*x)
    {
    (*x)+=5;
    printf("Value of x in byref is %d\n",(*x));
    }
    
    int main()
    {
    int x=5;
    int* y=&x;
    
    byvalue(x);
    printf("x in main is %d\n",x);
    byref(y);
    printf("x in main is %d\n",x);
    system("PAUSE");
    return 0;
    }
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    5
    a call by value passes only the-value-of a variable, while a call by reference passes a reference (address usually) to a variable so that it's value can be altered

  4. #4
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Passing by reference is faster than passing by value (and it saves a little bit of memory), but when passing by value, you can't accidently change the value of a variable.

  5. #5
    Anti-Terrorist
    Join Date
    Aug 2001
    Location
    mming, Game DevelopmentCSR >&<>&2Minimization of boolean functions, PROM,PLA design >&0>&WA, USA guitar, dogsCommercial Aviation >&>>&USAProgramming
    Posts
    742
    When you pass by value, a copy of the object is created in the called function and placed on that functions memory stack, whereas references use an address to the original value in the caller, this requires a pointer to be created but not a whole copy of the object.
    I compile code with:
    Visual Studio.NET beta2

Popular pages Recent additions subscribe to a feed