បង្រៀបង ៀបរវារ Pass By Reference នរ
ិ Pass by Pointer
Difference Pass By Reference Pass by Pointer
Syntax and - បងរកើតងោយង្ប្ើ ាស់ & មុខ Parameter - ង្ប្ើ ាស់ Pointer(*) មុខ Parameter
Declaration - ង្បើ្ាស់ *(Dereference) ង ើមបកើ ែក្បតំលៃែនុរ Function
Pass - Pass variable directly - ង្ប្ើ ាស់ &(Address of) ងេៃងៅ
Use - មិន្តូវការ្រប់្ររ Pointer - ្តូវការ្រប់្ររ Pointer
- Syntax ្សង ៀរ Pass by value o &(Address of): ចំៃរ Memory Address of Variable
- បុកនែវាក្ប្បួៃតំលៃែនុរ Function o *(Dereference): Access ងៅកាន់តំលៃរបស់ Memory
Address របស់ Variable
Memory Acces - Operate ងៅងៃើ Original Variable ងោយគ្មាន្តូវការ - Operate ងៅងៃើ Memory Address របស់ Variable ងោយង្បើ
រណនា Memory Address *(Dereference) ង ើមបកើ ែក្បតំលៃ
Nullability - មិនអាច null(្តូវកតមាន Object or Variable) - អាចមាន null or nullptr
Use Case - ចរ់កែក្បតំលៃែនុរ Function ងោយមន
ិ ង្ប្ើ ាស់ - ង្ប្ើ ាស់ Dynamic Memory
Pointer - null pointer(ទងទ)
- សំរាប់ Object or Variable ំៗងោយគ្មានការ Copy
Syntax - Create return-type func-name(data-type &par){ return-type func-name(data-type *par){
Statements; *par = value;
} }
Syntax - Calling int main(){ int main(){
func-name(variable); func-name(&variable);
} }
ង្បៀបង ៀបរវារ Pass By Reference និរ Pass By Pointer
Pass By Reference Pass By Pointer
C++ Code: C++ Code:
#include<iostream> #include<iostream>
#include<math.h> #include<math.h>
using namespace std; using namespace std;
//Pass By Reference //Pass By Pointer
//Function Definition //Function Definition
void increment(int &x){ void increment(int *x){
x = 20; *x = 20;
} }
int main(){ int main(){
//Variable Declaration //Variable Declaration
int value = 5; int value = 5;
cout << "Before Increment: " << value << endl;//5 cout << "Before Increment: " << value << endl;//5
increment(value); increment(&value);
cout << "After Increment: " << value << endl;//5 cout << "After Increment: " << value << endl;//20
return 0; return 0;
} }
Output: Output:
C++ Code: C++ Code:
#include<iostream> #include<iostream>
#include<math.h> #include<math.h>
using namespace std; using namespace std;
//Pass By Reference //Pass By Pointer
//Function Definition //Function Definition
void Swap(int &x, int &y){ void Swap(int *x, int *y){
int temp = x;//Address of a int temp = *x;//Address of a
x = y;//Address of b *x = *y;//Address of b
y = temp;//Address of a *y = temp;//Address of a
} }
int main(){ int main(){
//Variable Declaration //Variable Declaration
int a = 5; int a = 5;
int b = 10; int b = 10;
cout << "Before Increment: " << endl; cout << "Before Increment: " << endl;
cout << "--a: " << a << endl;//--a: 5 cout << "--a: " << a << endl;//--a: 5
cout << "--b: " << b << endl;//--b: 10 cout << "--b: " << b << endl;//--b: 10
Swap(a,b); Swap(&a,&b);
cout << "After Increment: " << endl; cout << "After Increment: " << endl;
cout << "--a: " << a << endl;//--a: 10 cout << "--a: " << a << endl;//--a: 10
cout << "--b: " << b << endl;//--b: 5 cout << "--b: " << b << endl;//--b: 5
return 0; return 0;
} }
Output: Output: