Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

slightly less undefined behavior in Vector3D and Vector4D implementation #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions CMU462/include/CMU462/vector3D.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

#include <ostream>
#include <cmath>
#include <array>

namespace CMU462 {

Expand All @@ -14,8 +15,14 @@ namespace CMU462 {
class Vector3D {
public:

// components
double x, y, z;
/**
* this type-punning is still technically undefined behavior, but all major
* compilers explicitly define it (gcc, clang, msvc)
*/
union {
struct { double x; double y; double z; };
std::array<double, 3> data;
};

/**
* Constructor.
Expand Down Expand Up @@ -43,12 +50,12 @@ class Vector3D {

// returns reference to the specified component (0-based indexing: x, y, z)
inline double& operator[] ( const int& index ) {
return ( &x )[ index ];
return data[index];
}

// returns const reference to the specified component (0-based indexing: x, y, z)
inline const double& operator[] ( const int& index ) const {
return ( &x )[ index ];
return data[index];
}

inline bool operator==( const Vector3D& v) const {
Expand Down
14 changes: 10 additions & 4 deletions CMU462/include/CMU462/vector4D.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,14 @@ namespace CMU462 {
class Vector4D {
public:

// components
double x, y, z, w;
/**
* this type-punning is still technically undefined behavior, but all major
* compilers explicitly define it (gcc, clang, msvc)
*/
union {
struct { double x; double y; double z; double w; };
std::array<double, 4> data;
};

/**
* Constructor.
Expand Down Expand Up @@ -63,12 +69,12 @@ class Vector4D {

// returns reference to the specified component (0-based indexing: x, y, z)
inline double& operator[] ( const int& index ) {
return ( &x )[ index ];
return data[ index ];
}

// returns const reference to the specified component (0-based indexing: x, y, z)
inline const double& operator[] ( const int& index ) const {
return ( &x )[ index ];
return data[ index ];
}

// negation
Expand Down