zoukankan      html  css  js  c++  java
  • call by reference and copy/restore

    转自:http://stackoverflow.com/questions/8848402/whats-the-difference-between-call-by-reference-and-copy-restore

    Main code:

    #include <stdio.h>
    
      int a;
    
      int main() {
          a = 3;
          f( &a, 4);
          printf("&#37;d
    ", a);
          return 0;
      }
    

    Call by Value:

    f(int x, int &y){
        // x will be 3 as passed argument
        x += a;
        // now a is added to x so x will be 6
        // but now nothing is done with x anymore
        a += 2*y;
        // a is still 3 so the result is 11
    }
    

    Value is passed in and has no effect on the value of the variable passed in.

    Call by Reference:

    f(int x, int &y){
        // x will be 3 as passed argument
        x += a;
        // now a is added to x so x will be 6
        // but because & is used x is the same as a
        // meaning if you change x it will change a
        a += 2*y;
        // a is now 6 so the result is 14
    }
    

    Reference is passed in. Effectively the variable in the function is the same as the one outside.

    Call with Copy/Restore:

    int a;
    void unsafe(int x) {
        x= 2; //a is still 1
        a= 0; //a is now 0
    }//function ends so the value of x is now stored in a -> value of a is now 2
    
    int main() {
        a= 1;
        unsafe(a); //when this ends the value of a will be 2
        printf("&#37;d
    ", a); //prints 2
    }
    

    Value is passed in and has no effect on the value of the variable passed in UNTIL the end of the function, at which point the FINAL value of the function variable is stored in the passed in variable.

    The basic difference between call by reference and copy/restore then is that changes made to the function variable will not show up in the passed in variable until after the end of the function while call by reference changes will be seen immediately.

  • 相关阅读:
    20151019
    20151013
    20150810
    20150626
    20150625
    20150530
    HTML特殊字符大全
    label标签跳出循环
    IIS 负载均衡
    .NET代码执行效率优化
  • 原文地址:https://www.cnblogs.com/xubenben/p/3145261.html
Copyright © 2011-2022 走看看