Sorry, bad proofreading.  The #4 example should read:

struct copy { char buf[128]; };
#define copyof(str) &({ struct copy cp; strcpy(cp.buf, str); cp; }).buf[0]
int main(int argc, char **argv) {
       printf("%s %s\n", copyof("hello"), copyof("world"));
}


-----Original Message-----
>From: Jamax <[EMAIL PROTECTED]>
>Sent: May 28, 2008 12:07 PM
>To: gcc@gcc.gnu.org
>Subject: Statement expressions problem returning arrays.
>
>Hello.  I have some complex statement-expressions that I am having trouble 
>with and this seemed like the more technical mailing list.  I have boiled them 
>down to these small examples:
>
>#1:
>
>#define copyof(str) ({ char buf[sizeof(str)]; strcpy(buf, str); buf; })
>int main(int argc, char **argv) {
>   printf("%s %s\n", copyof("hello"), copyof("world"));
>}
>
>That produces the output "hello world" when compiled with no optimization, but 
>"hello hello" when compiled with -O or greater (but not with just the flags 
>enabled by -O).  It was my impression that a character array allocated on the 
>stack was kind of like a value rather than a pointer (like char arrays are 
>inside a struct), so it seems like the statement-expression should be 
>returning a copy of the whole array rather than a copy of a pointer to its 
>previous location on the stack.
>
>#2:
>
>#define copyof(str) ({ char buf[128]; strcpy(buf, str); buf; })
>int main(int argc, char **argv) {
>   printf("%s %s\n", copyof("hello"), copyof("world"));
>}
>
>That produces "hello hello" no matter what optimization is used.
>
>#3:
>
>struct copy { char buf[128]; };
>#define copyof(str) ({ struct copy cp; strcpy(cp.buf, str); cp; }).buf
>int main(int argc, char **argv) {
>       printf("%s %s\n", copyof("hello"), copyof("world"));
>}
>
>Memory fault.
>
>#4:
>
>struct copy { char buf[128]; };
>#define copyof(str) ({ struct copy cp; strcpy(cp.buf, str); cp; }).buf
>int main(int argc, char **argv) {
>       printf("%s %s\n", copyof("hello"), copyof("world"));
>}
>
>That 'correctly' produces "hello world" with any optimization level.
>
>So my question is, are those all the expected behavior (#1 through #3 are not 
>valid)?  From my 'ok' knowledge of C and gnu extensions it seems like all four 
>should produce "hello world".
>
>These results are from 4.1.2 and 4.2.3 on Gentoo, processor is Pentium M.   
>Includes for stdio, string not shown.
>



Reply via email to