patterncppMinor
Coding Practice - Float* -> Vector3* cast
Viewed 0 times
practicefloatcastvector3coding
Problem
If you were given the following:
Which is considered better practice?
The advantage to the latter option is of course far more explicit, and carries all the advantages/disadvantages that contains; but may not be portable depending on the assertions you can make.
#include
struct vec {
float x,y,z;
vec(float x, float y, float z) : x(x), y(y), z(z) {}
};
int main() {
float verts[] = {1,2,3,4,5,6,7,8,9}; // length guaranteed to be a multiple of 3
assert(sizeof(vec) == sizeof(float) * 3);
// Option 1
for (int i = 0; i (verts)[i];
// ...
}
// Option 2
for (int i = 0; i < 9; i += 3) {
vec a(verts[i], verts[i+1], verts[i+2]); // -O3 averts the copy, so d/w
// ...
}
return 0;
}Which is considered better practice?
The advantage to the latter option is of course far more explicit, and carries all the advantages/disadvantages that contains; but may not be portable depending on the assertions you can make.
Solution
I would go with a 3rd option that is closest to option 2. But instead of taking the three parameters separately in the constructor, take an array of floats.
struct vec {
float x,y,z;
vec(float fv[]) : x(fv[0]), y(fv[1]), z(fv[2]) {}
};
int main() {
float verts[] = {1,2,3,4,5,6,7,8,9};
for (int i = 0; i < 9; i += 3) {
const vec a(&verts[i]);
// ...
}
return 0;
}Code Snippets
struct vec {
float x,y,z;
vec(float fv[]) : x(fv[0]), y(fv[1]), z(fv[2]) {}
};
int main() {
float verts[] = {1,2,3,4,5,6,7,8,9};
for (int i = 0; i < 9; i += 3) {
const vec a(&verts[i]);
// ...
}
return 0;
}Context
StackExchange Code Review Q#4384, answer score: 3
Revisions (0)
No revisions yet.