5 ms·
As someone who avoids C++ these days ... Is this a compile time FizzBuzz? `(char*)&1[""]` is the empty string here returning its data segment address as the o
by jessermeyer 4y ago
As someone who avoids C++ these days ...
Is this a compile time FizzBuzz?
`(char*)&1[""]` is the empty string here returning its data segment address as the offset? Not sure about the purpose of `1`.
Is the iteration achieved by the constructor basically re-invoking itself?
- vardump 4y agoIt's a static initialization time FizzBuzz. In this case, I think it's executed before main() is called, and not at compile time. Unless, of course, you have a very clever compiler that determines memory allocation is not actually allocating anything and that the output is a static string, and there are no side effects. Such a clever compiler could optimize it all into just one "puts" call.
- jessermeyer 4y agoNeither GCC nor Clang bake the final string into the data segment. If I had to guess, printf is the one preventing the more fancy optimizations to take place.
- vardump 4y agoI think so too. Also, depending on stdlib output buffering, the external I/O behavior of 100 puts calls is potentially different from just one call. In other words, there might be a different number of stdout write-calls.
- bno1 4y ago&1[""] is the same as &(""[1])
- jessermeyer 4y agoAh, so it's the nil address?
- leni536 4y agoNo, it's the address past the end of the array {'\0'}.
- jessermeyer 4y agoMind to unpack that for me? Here's how I unpack this: ""[1] is the 0 (termination) byte. The 0 byte is then interpreted as an address -- the nil address. But what's the use of asking for the address of the null terminator? Where is that stored exactly?
- jussij 4y agoThe "" will define a null terminated char array to represent the string. But as it string contains no text it's a char array that only requires one byte (i.e. it contains nothing but the null termination character). Now the first character of that char array is found here: ""[0] The second character is found here: ""[1] So the address of the second character is found here: &""[1] But as the string was represented by one byte char array that second address is past the end of the string. So it's actually an undefined address.
- leni536 4y agoNit: one past end of an array is actually fine as an address.
- jussij 4y agoNot always. Consider this 'test.cpp' example: #include <stdio.h> #include <string.h> struct a_struct { char a[1]; char b[2]; a_struct() { strcpy(a, ""); strcpy(b, "b"); } } x; int main() { printf("before:\n"); printf("a : '%s'\n", x.a); printf("b : '%s'\n", x.b); char *c = &1[x.a]; *c = 'c'; printf("after:\n"); printf("a : '%s'\n", x.a); printf("b : '%s'\n", x.b); //b is now corrupt } Compile and running this code: C:\temp>g++ test.cpp C:\temp>a.exe before: a : '' b : 'b' after: a : '' b : 'c'