avr-gcc-list
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

RE: [avr-gcc-list] string initialization using "" and { }


From: Stu Bell
Subject: RE: [avr-gcc-list] string initialization using "" and { }
Date: Wed, 27 May 2009 08:13:24 -0600

> Compiling the following code:
> 
> /* ... */
> 
> int main() {
>   char test1[] = "abd";
>   char test2[] = { 'a', 'b', 'd', '\0' };
>   /* ... */
> 
> }
> 
> shows this:
> 
>   char test1[] = "abd";
>      8c0:     80 91 00 01     lds     r24, 0x0100
>      8c4:     90 91 01 01     lds     r25, 0x0101
>      8c8:     a0 91 02 01     lds     r26, 0x0102
>      8cc:     b0 91 03 01     lds     r27, 0x0103
>      8d0:     8f 87           std     Y+15, r24       ; 0x0f
>      8d2:     98 8b           std     Y+16, r25       ; 0x10
>      8d4:     a9 8b           std     Y+17, r26       ; 0x11
>      8d6:     ba 8b           std     Y+18, r27       ; 0x12
>   char test2[] = { 'a', 'b', 'd', '\0' };
>      8d8:     81 e6           ldi     r24, 0x61       ; 97
>      8da:     8b 8b           std     Y+19, r24       ; 0x13
>      8dc:     82 e6           ldi     r24, 0x62       ; 98
>      8de:     8c 8b           std     Y+20, r24       ; 0x14
>      8e0:     83 e6           ldi     r24, 0x64       ; 100
>      8e2:     8d 8b           std     Y+21, r24       ; 0x15
>      8e4:     1e 8a           std     Y+22, r1        ; 0x16
> 
> Why the difference?

My SWAG (Sophisticated Wild A** Guess) is that the compiler sees "abd"
as a single constant whereas it sees 'a', 'b', 'd', '\0' as four
constants.  Since it understands the concept of a string as a constant,
it stores the string constant in flash and then copies it into the stack
frame (your first example).  In the second case, since the constants fit
in a single byte, it copies them from immediate values directly in the
code.

This can actually be a good thing.  For example,

   char foo;
   . . .
   if ( foo == '\n' ) . . .

In the above example, it will be easier to compile the constant '\n'
directly into the code as an immediate value rather than setting up a
constant value somewhere.

Best regards, 

Stu Bell 
DataPlay (DPHI, Inc.) 





reply via email to

[Prev in Thread] Current Thread [Next in Thread]