Thread: Car assignment help

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Dec 2008
    Posts
    104
    Basically, when calling a function that requires (a) parameter(s) in C, you have two options; you can pass by value, or by reference.

    When passing by value, the value of the parameter you are caling the function with, will be copied, and will NOT be the same reference.

    Here's code for a small illustration:
    Code:
    void add(int);
    
    int main(int argc, char **argv)
    {
    
        int i = 2;
        add(i);
    
        return 0;
    
    }
    
    void add(int a)
    {
        a += 5;
    }
    In main, after calling the function add(int), passing the local variable 'i' as parameter, 'i's value will not be modified whatsoever, because we are passing 'i' by value, and not by reference; so, therefore, the value of 'i' is copied into the function.

    When passing by reference, the variable passed as a parameter will be modified according to the function.

    Example:
    Code:
    void add(int *);
    
    int main(int argc, char **argv)
    {
    
        int i = 2;
        add(&i);
    
        return 0;
    
    }
    
    void add(int *a)
    {
        (*a) += 5;
    }
    In this application, after calling the add(int*) function, passing 'i' as parameter, the value of 'i' will be changed. '5' will be added to the variable passed in the function (i) and since we are using pass by reference, it will modify the passed argument directly; in this case '1'.
    Last edited by abraham2119; 05-09-2009 at 08:37 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  2. Replies: 1
    Last Post: 10-27-2006, 01:21 PM
  3. OpenGL coordinates
    By Da-Nuka in forum Game Programming
    Replies: 5
    Last Post: 01-10-2005, 11:26 AM
  4. i really need help here
    By Unregistered in forum C Programming
    Replies: 4
    Last Post: 04-09-2002, 10:47 PM
  5. I need help with an algorithm
    By Unregistered in forum C Programming
    Replies: 1
    Last Post: 04-07-2002, 07:58 PM