I'm starting with C++
programming and I believe I have got a grasp about pointers. However I'm trying to understand the best practices for pointers and functions while using struts.
Toy example code
I have made below Toy example code to exemplify two ways to perform same thing:
#include <stdio.h>
struct rectangle {
int width;
int length;
};
void printRect(rectangle rect) {
printf("Rectangle: width=%d, length=%d\n",rect.width, rect.length);
}
void doubleSizeRectangle_1(rectangle *rect) {
rect->width = rect->width*2;
rect->length = rect->length*2;
}
rectangle doubleSizeRectangle_2(rectangle rect) {
rectangle *r = ▭
r->width = r->width*2;
r->length = r->length*2;
return *r;
}
rectangle doubleSizeRectangle_3(rectangle rect) {
rect.width = rect.width*2;
rect.length = rect.length*2;
return rect;
}
int main()
{
rectangle rect;
rect.width = 2;
rect.length = 5;
rectangle *rect_pointer = new rectangle;
rect_pointer = ▭
printRect(rect);
printRect(*rect_pointer);
printf("Applying functions:\n");
doubleSizeRectangle_1(rect_pointer);
printRect(rect);
rect = doubleSizeRectangle_2(*rect_pointer);
printRect(rect);
rect = doubleSizeRectangle_3(*rect_pointer);
printRect(rect);
}
That code returns following output:
Rectangle: width=2, length=5
Rectangle: width=2, length=5
Applying functions:
Rectangle: width=4, length=10
Rectangle: width=8, length=20
Rectangle: width=16, length=40
The first two prints are just to check about pointers usage.
The remaining prints are to check the three functions doubleSizeRectangle_1
, doubleSizeRectangle_2
and doubleSizeRectangle_3
that perform same actions in different ways. The first one returns void
and uses a pointer as input, whereas the second and third one have a variable as input and return a rectangle struct
. Third option seems better than second, but would like to confirm. I'm not sure about the first one compared to the rest.
Question
Which option would be better in terms of best practice and why? Is there any of these options better in terms of avoiding memory leaks? May there be any other ways using pointers, and would those be even better than those I posted?