Say I have global variables defined in a TU such as:
extern const std::string s0{"s0"};
extern const std::string s1{"s11"};
extern const std::string s2{"s222"};
// etc...
And a function get_1
to get them depending on an index:
size_t get_1(size_t i)
{
switch (i)
{
case 0: return s0.size();
case 1: return s1.size();
case 2: return s2.size();
// etc...
}
}
And someone proposes replacing get_1
with get_2
with:
size_t get_2(size_t i)
{
return *(&s0 + i);
}
- Are global variables defined next to each other in a translation unit like this guaranteed to be stored contiguously, and in the order defined?
- Ie will
&s1 == &s0 + 1
and&s2 == &s1 + 1
always be true? - Or can a compiler (does the standard allow a compiler to) place the variables
s0
higher thans1
in memory ie. swap them?
- Ie will
- Is it well defined behaviour to perform pointer arithmetic, like in
get_2
, over such variables? (that crucially aren't in the same sub-object or in an array etc., they're just globals like this)- Do rules about using relational operators on pointers from https://stackoverflow.com/a/9086675/8594193 apply to pointer arithmetic too? (Is the last comment on this answer about
std::less
and friends yielding a total order over anyvoid*
s where the normal relational operators don't relevant here too?)
- Do rules about using relational operators on pointers from https://stackoverflow.com/a/9086675/8594193 apply to pointer arithmetic too? (Is the last comment on this answer about
Edit: this is not necessarily a duplicate of/asking about variables on the stack and their layout in memory, I'm aware of that already, I was specifically asking about global variables. Although the answer turns out to be the same, the question is not.