C++ Reference Variable

오범준·2021년 7월 5일
0

C++

목록 보기
1/2

Characteristic of "Reference Variable"

1) Have to be Initialized

int lvalue = 3;
int &ref ; // error

2) Have to be Initialized with 'l-value'

"l-value" vs "r-value"

l-value : value that has an memory assigned by OS
r-value : x ex) literal, number

int l_value = 3; // l_value having value '3' with memory assigned by OS
int &ref = l_value; // ok
int &ref = 3; // no

3) Value, Address All same with " original variable"

int l_value = 3;
int &ref = l_value;

cout << ref << l_value << endl;   // same
cout << &ref << &l_value << endl; // same

4) no need to "copy" variable when used as function parameter

  • Much more Effective In terms of Processing
int main()
{
	int l_value = 3;
    doSth(l_value)
}

// - variable 'l_value' itself is inserted as parameter
// - with no 'variable copying' process 
void doSth(int &l_value)
{
	cout << "ref" << ref << endl;
}

// - variable 'l_value' is copied
// address of 'l_value' in 'main' &&
// address of 'l_value' in 'doSth'
// is different , since new variable 'l_value' is generated as a result of 'copy'
void doSth(int l_value)
{
	cout << "ref" << ref << endl;
}
profile
Dream of being "물빵개" ( Go abroad for Dance and Programming)

0개의 댓글