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

前端 未结 7 1013
盖世英雄少女心
盖世英雄少女心 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:21

    You need to assign the return value of FindArea to rArea. At the moment, FindArea assigns the product to its local variable of the same name.

    Alternatively, you can pass the address of main's rArea to modify that, that would look like

    FindArea(&rArea, rBase, rHeight);
    

    in main with

    void FindArea(int * rArea, int rBase, int rHeight) {
        *rArea = rBase * rHeight;
    }
    
    0 讨论(0)
  • 2020-12-22 14:30

    take rArea by pointer:

    int FindArea(int *, int , int);
    
    ...
    
    FindArea (&rArea , rBase , rHeight);
    
    ...
    
    
    
    int FindArea (int *rArea , int rBase , int rHeight)
    {
     *rArea = (rBase * rHeight);
    
     return (*rArea);
    
    }
    
    0 讨论(0)
  • 2020-12-22 14:34

    Your basic problem is you don't understand how to get values out of a function. Change the relevant lines to:

    int FindArea(int rBase, int rHeight);  // prototype
    

    and

    int area = FindArea(rBase, rHeight);
    

    and

    int FindArea(int rBase, int rHeight)
    {
         return rBase * rHeight;
    }
    
    0 讨论(0)
  • 2020-12-22 14:35

    Because you are not storing the return value. The code won't compile in its present form.

    1. Call it as:

      rArea = (rBase , rHeight);
      
    2. Change the function to:

      int FindArea (int rBase ,int rHeight)  
      {  
          return (rBase * rHeight);  
      }
      
    3. Change the prototype to:

      int FindArea(int , int);
      
    0 讨论(0)
  • 2020-12-22 14:37
    FindArea (rArea , rBase , rHeight);
    

    doesn't work like you think it does. In C, parameters are passed by value; that means modifying area inside the function modifies only a local copy of it. You need to assign the return value of the function to the variable:

    int FindArea(int w, int h) { return w * h; }
    
    int w, h, area;
    
    // ...
    area = findArea(w, h);
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题