C++ pass by VALUE vs pass by REFERENCE? 📧

preview_player
Показать описание
#pass #value #reference

Pass by value vs pass by reference tutorial example explained
Рекомендации по теме
Комментарии
Автор

#include <iostream>

void swap(std::string &x, std::string &y);

int main()
{
std::string x = "Kool-Aid";
std::string y = "Water";

swap(x, y);

std::cout << "X: " << x << '\n';
std::cout << "Y: " << y << '\n';

return 0;
}
void swap(std::string &x, std::string &y){
std::string temp;
temp = x;
x = y;
y = temp;
}

BroCodez
Автор

many thanks sir, my many confusions are cleared. I have been watching this series from one week before, Sir did the 👏🙌good job

ganapathipasupathi
Автор

i have been trying to do this, now i realize after watching this video that i was doing it backwards. ahaha thanks man

lastwaveundergroundsaviour
Автор

So if i understand this correctly, is this the same concept of variable scope? where basically when you pass by value you get local versions of X and Y, which is what the function swaps, rather than the main()value?

xavierboudrot
Автор

Nice Video. But should also say that pass-by-value/reference means the same as call-by-value/reference.

FrederikWollert
Автор

1:58
Why don’t we just return X and Y? Void function don’t have return types so we change the “void” to a “string” right? Or is there no such thing as a string function?

dyvflui
Автор

Is it a good practice to always pass variables by reference to the functions?

renusoni
Автор

I see mine are swapping even without passing by reference, why

kristijanlazarev
Автор

if this is the case shouldnt we always pass parameters by reference?

garyalvarado
Автор

#include<iostream>

void _swap(std::string x, std::string y); // passing by value
// does not change value in place due to varying scopes(different memory addresses)

void swap(std::string &x, std::string &y); // passing by reference
// "reference" to memory address so that it changes in place

int main()
{
std::string x = "Kool-Aid";
std::string y = "Water";

_swap(x, y);

std::cout <<
std::cout << "Passing by value...\n";
std::cout << "x: " << x << "\n";
std::cout << "y: " << y << "\n";

swap(x, y);

std::cout << "\nPassing by reference...\n";
std::cout << "x: " << x << "\n";
std::cout << "y: " << y << "\n";
std::cout <<

return 0;
}

void _swap(std::string x, std::string y)
{
std::string temp;
temp = x;
x = y;
y = temp;
}

void swap(std::string &x, std::string &y)
{
std::string temp;
temp = x;
x = y;
y = temp;
}

lyfisntdaijobu