Passing structs

Similar to passing a fundamental type, we can pass structs to functions and return structs from functions. For example,

struct Pixel
{
    int x;
    int y;
};
 
void printPixel(const Pixel pixel)
{
    std::cout << pixel.x << "\n";
    std::cout << pixel.y << "\n";
}
 
int main(int argc, char const *argv[])
{
    Pixel pixel{3, 2};
    printPixel(pixel);
}

It is also possible to pass by reference which saves the copy of the struct. We can modify printPixel parameter definition to support references.

void printPixel(const Pixel &pixel)
{
    std::cout << pixel.x << "\n";
    std::cout << pixel.y << "\n";
}

Here we have created a Pixel variable and then passing it to the function. We can directly pass Pixel to the function as shown below.

printPixel(Pixel {1, 2}); // should be used.
printPixel({4, 5}); // should be avoided.

In the latter case, the type is deduced from the function. This should generally be avoided as it is not informative as compared to previous one.

Returning structs

When we need to return multiple values from a function, a struct can be useful in this case. Following example shows where a function return a struct.

Pixel createPixel(int x, int y)
{
    return Pixel{x, y};
}

This creates a temporary object which gets copied to the caller and then destroyed. For example,

Pixel result{createPixel(1, 2)};
printPixel(result);

What happens here?

printPixel(createPixel(1, 2));

createPixel returns a temporary struct which gets destroyed. Here, we are also not copying into a variable to be used later. Will printPixel print something or the program will crash? Please note that printPixel accepts struct by reference.

In my case, it successfully prints the struct maybe because the return temporary object stays until the full function call expression finishes.

References

  1. https://www.learncpp.com/cpp-tutorial/passing-and-returning-structs/