what is value- and reference semantics and the difference

有些话、适合烂在心里 提交于 2019-11-29 16:45:38

In the reference semantic, an argument refers to the original object, being it for reading or for writing.

In the value semantic, an argument is just the value of an object, i.e. a copy instead of the original. Of course, if you alter this copy with some side effects, the original element remains unchanged.

Example of passing by value:

int f(int a)   /* argument a is passed by value (local variable containing a copy)  */ 
{
    a++;      /* increments the local variable */
    return (a+5);   /* return a value */  
}

int main (int ac, char**av) {
    int b=7, c; 
    c = f(b);  /* b will be copied. The original value is unchanged */
    printf ("b=%d c=%d\n", b, c);  /* prints 7 and 13 */
}

Example of passing by reference:

int fr(int* pa)   /* argument pa is a pointer refering to original value  */ 
{
    *pa+=1;      /* increments value pointed to (the original variable) */
    return (*pa+5);   /* return by value */  
}

int main (int ac, char**av) {
    int b=7, c; 
    c = fr(&b);  /* The original value in b is changed */
    printf ("b=%d c=%d\n", b, c);  /* prints 8 and 13 */
}

Returning by reference is less obvious. Tt's used for example to return a reference received as argument, or related to it. Or a reference to a dynamically allocated object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!