Why doesn't return modify the value of a parameter to a function

前端 未结 7 1088
盖世英雄少女心
盖世英雄少女心 2020-12-22 13:57

Possible Duplicate:
How to modify content of the original variable which is passed by value?

I am building a

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-22 14:45

    You intialize rArea to 0. Then, you pass it into FindArea by value. This means none of the changes to rArea in the function are reflected. You don't make use of the return value, either. Therefore, rArea stays 0.

    Option 1 - Use the return value:

    int FindArea(int rBase, int rHeight) {
        return rBase * rHeight;
    }
    
    rArea = FindArea(rBase, rHeight);
    

    Option 2 - Pass by reference:

    void FindArea(int *rArea, int rBase, int rHeight) {
        *rArea = rBase * rHeight;
    }
    
    FindArea(&rArea, rBase, rHeight);
    

提交回复
热议问题