Lesson 8 of 24

References மற்றும் Pass by ReferenceReferences and Pass by Reference

9 min 30 XP

Reference (int& r = x) என்பது ஒரு variable-க்கான மாற்றுப் பெயர். Function parameter-ஐ reference ஆக்கினால் pointers இல்லாமலேயே மூல variable-ஐ மாற்றலாம். பெரிய objects-ஐ copy செய்யாமல் அனுப்ப const& பயன்படுத்துங்கள்.

A reference (int& r = x) is another name for a variable. Make a parameter a reference and the function can change the caller's variable without pointers. Use const& to pass big objects without copying them.

Example: edit me and press Run

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.

Pointer vs reference: reference ஒருபோதும் null ஆகாது, வேறு variable-ஐக் குறிக்க மாற்ற முடியாது. இது ஒரு பிரபல interview கேள்வி.

Pointer vs reference: a reference can't be null and can't be re-pointed to another variable. A popular interview question.

Challenge

+30 XP

void sortThree(int& a, int& b, int& c) என்ற function எழுதுங்கள்: மூன்றையும் ஏறு வரிசையில் மாற்றும். main()-ல் மூன்று எண்களைப் படித்து, sortThree அழைத்து print செய்யுங்கள். Input: 9 2 5 → Output: 2 5 9

Write void sortThree(int& a, int& b, int& c) that rearranges the three values into ascending order. In main(), read three numbers, call it and print them. Input: 9 2 5 → Output: 2 5 9

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.