2017년 11월 20일 월요일

(퍼옴) Pass by value and Pass by reference

Here is  a link to the original page:

https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value

Though the author writes that the analogy is not exact, it feels like the old explanation is
more natural and easy.
In short,

Analogy: Transferring a webpage,

Pass by reference: give the URL of webpage and authority to change.
Pass by value: give the printout of webpage

By default Fortran uses 'pass by reference' and C++ uses 'pass by value'.

In Fortran, subroutine calls f(x,y) and do something to the x and y then
it makes difference. In Fortran, one uses INTENT to avoid accidental change of contents.

In C++, since the default is 'pass by value', it does not change the original variable.
However, it would be inefficient to pass all big object by value. So, sometimes passing
a reference by using ' & var' is more convenient.

Difference between '&' and '*' in C++:

They are similar in the sense that they refers something in the memory.

Here is an original explanation:
https://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1047588532&id=1043284376

https://stackoverflow.com/questions/28778625/whats-the-difference-between-and-in-c

In short, '&' is used for objects reference but '*' is for a pointer of address.
( ** is used for a pointer of a pointer. For example, "char** argv" or "char* argv[]"
argv is an array of characters. Each char* is a pointer of a first character in string.
Then, char** is a double pointer for a pointer of a pointer to a character. )


* and & as type modifiers

  • int i declares an int.
  • int* p declares a pointer to an int.
  • int& r = i declares a reference to an int, and initializes it to reference i.
    C++ only. Note that references must be assigned at initialization, therefore int& r; is not possible.
Similarly:
  • void foo(int i) declares a function taking an int (by value, i.e. as a copy).
  • void foo(int* p) declares a function taking a pointer to an int.
  • void foo(int& r) declares a function taking an int by reference. (Again, C++ only)

* and & as operators

  • foo(i) calls foo(int i). The parameter is passed as a copy.
  • foo(*p) dereferences the int pointer p and calls foo(int i) with the int pointed to by p.
  • foo(&i) takes the address of the int i and calls foo(int* i) with that address.

설명: 비록 C++ compiler 는 (int* p) and  (int *p) 를 구분하지 않지만,의미는 다르다.
(1) (int* p) 는 p 라는 포인터를 선언하는데, 그 포인터가 가리키는 것이 정수라는 의미이다. 
    foo(int* p) 라고 정의하면, 함수 foo는 포인터를 변수로 받는데, 그 포인터는 정수 변수를 가리킨다는 것이다. 때문데 foo를 사용할 때는 foo( &i) 와 같이 사용하거나, foo(p) 로 pointer를 주어야한다.
(2) 반면, foo(int& r) 로 선언하는 경우는 foo가 변수 r을 받되 call by reference로 받는다는 의미이다. 때문에 사용할 때는 foo(i) 로 사용한다. ( foo(p)나 foo(&r) 은 옳지않다.)


(tl;dr) So in conclusion, depending on the context:

댓글 없음:

댓글 쓰기