Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

function - Parameter Passing in C - Pointers, Addresses, Aliases

Could someone please explain the difference between parameter passing in C please? According to professor notes there are 4 different ways to pass parameters

  1. Call-by-value
  2. Call-by-address (pointer)
  3. Call-by-alias
  4. Global variable / Static variable

If you could please give an example, I would greatly appreciate that, and your work would be commended.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. Call-by-value

    Passing the value to a function as a parameter. If the function modifies the variable, the actual variable won't get changed.

    void fun1(int myParam)
    {
        myParam = 4;
    }
    
    void main()
    {
        int myValue = 2;
        fun1(myValue);
        printf("myValue = %d",myValue);
    }
    

    myValue will always be 2.

  2. Call-by-address (pointer)

    void fun1(int *myParam)
    {
        *myParam = 4;
    }
    void main()
    {
        int myValue = 2;
        fun1(&myValue);
        printf("myValue = %d",myValue);
    }
    

    Here we are passing the address of myValue to fun1. So the value of myValue will be 4 at the end of main().

  3. Call-by-alias

    There is no alias in C as per my understanding. It should be the C++ reference mechanism.

  4. Global variable / Static variable

    Global and static variables are variables stored in a common places, accessible by the caller and callee functions. So both caller and callee will be able to access and modify them.

    int myValue = 2;
    void fun1()
    {
        myValue = 4;
    }
    void main()
    {
        myValue = 2
        fun1();
        printf("myValue = %d",myValue);
    }
    

    As you can guess, the value of myValue will be 4 at the end of main().

Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...