STRUCTS

Can someone explain what is the purpose of the & in the print function and how it works. I tried running this with and without the & and got the same thing


#include <iostream>
struct DateStruct
{
int year;
int month;
int day;
};
void print(DateStruct &date)
{
std::cout << date.year << "/" << date.month << "/" << date.day;
}
int main()
{
DateStruct today{ 2020, 10, 14 }; // use uniform initialization
today.day = 16; // use member selection operator to select a member of the struct
print(today);
return 0;
}
That is a reference, and instead of making a copy of your today object to pass into the print() function it passes the object itself into the function.

Copying complex data types like your struct can be a performance hit that passing by reference (or pointer) avoids.

https://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/

Edited to add:

If I were to write this code I'd write the print function so I pass the referenced object as a constant.

void print(const DateStruct& date)

Outputting the struct's member data shouldn't alter the data, if the function does change the data your compiler will flag it as an error.

And PLEASE learn to use code tags. They make it easier to read and comment on source code.

You can edit your post and add them.

http://www.cplusplus.com/articles/jEywvCM9/
Last edited on
Topic archived. No new replies allowed.