Exforsys
+ Reply to Thread
Results 1 to 2 of 2

Passing Arguments to Functions

This is a discussion on Passing Arguments to Functions within the C and C++ forums, part of the Programming Talk category; I am trying different ways of passing arguments to functions in C++. I wrote the below program which passes arguments ...

  1. #1
    caradoc is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    122

    Passing Arguments to Functions

    I am trying different ways of passing arguments to functions in C++. I wrote the below program which passes arguments to function by Passing a pointer by value.

    void sample(int *t);
    main()
    {
    int x;
    int *p;
    x = 10;
    p = &x;
    sample(p);
    cout << "x is %d" << x << " \n";
    }

    void sample(int *i)
    {
    *i = *i + 1;
    }

    If I want to code the same function by using the concept of passing by reference how can I do that. Kindly guide me on the same.


  2. #2
    ashlee is offline Senior Member Array
    Join Date
    Apr 2006
    Answers
    108
    You can code the same function by using the concept of passing by reference in C++ as below:
    void sample(int &t);
    main()
    {
    int x;
    x = 10;
    sample(x);
    cout << "x is &#37;d" << x << " \n";
    }

    void sample(int &x)
    {
    x = x + 1;
    }

    In the above changes made to the reference passed in function sample will also be made to the original variable as it is passed by reference.


Latest Article

Network Security Risk Assessment and Measurement

Read More...