CPP 034 – Pass by value, reference, pointer

Bir fonksiyona parametre atarken nasıl davranması gerektiğini belirliyebiliriz. Temel olarak şey yapabiliriz.

  1. Değişkenin bir kopyasını oluşturup onu atabiliriz
  2. Kopya oluşturmadan değişkenin kendisini atabiliriz

Değişkenin kopyasını oluşturduğumuzda fonksiyon içinde yapılan işlemler kopyanın üzerinde yapılacağı için ana değşikeni etkilemez. Reference ile attığımızda ise direk olarak ana değişkeni gönderdiğimiz için fonksiyon içinde yapılan işlemler ana değişkeni etkiler.

#include <iostream>
using namespace std;

void pass_by_value(int input) {
	cout << "pass by value" << endl;
	cout << "adress of input: " << &input << endl;
	cout << "value of input: " << input << endl << endl;

}

void pass_by_reference(int& input){
	cout << "pass by reference" << endl;
	cout << "adress of input: " << &input << endl;
	cout << "value of input: " << input << endl << endl;

}
void pass_by_pointer(int* input) {
	cout << "pass by pointer" << endl;
	cout << "&input : " << &input << endl;
	cout << "input  : " << input << endl;
	cout << "*input : " << *input << endl << endl;

}
int main() {
	int sayi{ 5 };
	cout << "in main function" << endl;
	cout << "adress of sayi: " << &sayi << endl;
	cout << "value of sayi: " << sayi << endl << endl;

	pass_by_value(sayi);
	pass_by_reference(sayi);
	pass_by_pointer(&sayi);

}

// in main function
// adress of sayi : 00000081A4F2FAA4
// value of sayi : 5
// 
// pass by value
// adress of input : 00000081A4F2FA80
// value of input : 5
// 
// pass by reference
// adress of input : 00000081A4F2FAA4
// value of input : 5
// 
// pass by pointer
// & input : 00000081A4F2FA80
// input : 00000081A4F2FAA4
// * input : 5

Bir de pass by pointer seçeneğimiz var. Bu aslında 3. bir seçenek değil. Hibrit bir çözüm olarak düşünebilirsiniz. Burada pointerı atıyoruz ama poniter da nihayetinde bir değişken olduğu için ya pass by value ile ya da pass by reference ile gidecek:

#include <iostream>
using namespace std;

void passpointer_byvalue(int* ptr) {
	cout << "passpointer_byvalue" << endl;
	cout << "&ptr: " << &ptr << endl;
	cout << "ptr : " << ptr << endl << endl;

}
void passpointer_byreference(int*& ptr) {
	cout << "passpointer_byreference" << endl;
	cout << "&ptr: " << &ptr << endl;
	cout << "ptr : " << ptr << endl << endl;

}
int main() {
	int sayi{ 5 };
	int* ptr = &sayi;


	cout << "in main function" << endl;
	cout << "&ptr: " << &ptr << endl;
	cout << "ptr : " << ptr << endl << endl;

	passpointer_byvalue(ptr);
	passpointer_byreference(ptr);


}

// in main function
// & ptr: 0000004495FCFB18
// ptr : 0000004495FCFAF4
// 
// passpointer_byvalue
// & ptr: 0000004495FCFAD0
// ptr : 0000004495FCFAF4
// 
// passpointer_byreference
// & ptr: 0000004495FCFB18
// ptr : 0000004495FCFAF4


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *