I am trying to implement a "table" of references for setting various code elements by an index lookup. Most of the underlying variables are double, but a few are different types like unsigned char.
Here is a simplified example:
static unsigned char foo = 0; // Variable to set
static unsigned double bar = 0.0; // Variable to set
...
struct tableEntry {
double& ref; // Reference to one of the above
double min;
double max;
};
struct tableEntry entries[] {
{ bar, 0.0, 1.0 },
{ (double&)foo, 0x0, 0xff },
};
When attempting to assign bar via the table, everything is fine.
entries[0].ref = 1.0;
This results in entries[0].ref == 1.0, and bar == 1.0, as expected. However, when assigning foo via the table...
entries[1].ref = 1.0;
This results in a value mismatch somehow, as if the reference is not able to be interpreted correctly, or isn't even referring to the right object. After this assignment, entries[1].ref == 1, but foo == 0.
Is this undefined behavior by the language, or am I misusing or abusing something? It's possible it is a discrepancy in versions of the standard, as I tested a similar example on repl.it with C++17 and it worked as I was expecting. This is not working as expected when compiling with our target compiler using mex in MATLAB, using Visual Studio 2017 as the compiler.