Wednesday, July 17, 2024

c++ method intro pass by value versus by reference versus by pointer

//methodsIntro.cpp

#include <iostream>

void funByValue(int x)
{
	printf("yaaay by value %d\n", x);
	x = 22;
}

void funByReference(int &r)
{
	printf("yaaay by reference %d\n", r);
	r = 22;
}

void funByPointer(int *p)
{
	printf("yaay by pointer %d\n", *p);
	*p = 22;
}

int main()
{
	printf("yaay\n");
	
	int p = 21;
	funByValue(p);
	printf("p after %d\n", p);
	
	p = 21;
	funByReference(p);
	printf("p after %d\n", p);
	
	p = 21;
	funByPointer(&p);
	printf("p after %d\n", p);
	
	return 0;
}

//to compile
//g++ -o prog methodsIntro.cpp
//./prog

//yaay
//yaaay by value 21
//p after 21
//yaaay by reference 21
//p after 22
//yaay by pointer 21
//p after 22

Happy Sketching!