Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

Re: Finally, really, actually, starting off with C

2009-01-07 by Don Kinzer

>Why would I want to spend four bytes of RAM on that?
If your main() is in the form of an infinite loop and you're using a 
suitably high level of optimization (typically -Os is recommended), 
the code actually generated by the compiler doesn't waste any RAM or 
code space.

For example, if your main() looks like this:

int main(void)
{
  while(1)
  {
  }
  return(0);
}

The generated code will look something like this excerpt:
26a:	0e 94 3b 01 	call	0x276
26e:	0c 94 4e 48 	jmp	0x909c
00000276 <main>:
276:	ff cf       	rjmp	.-2

Leaving out the return statement (as is commonly done) produces the 
same result and no compiler warnings.

> Does C (or Winavr) init a declared variable to some
> defined state ALWAYS, or do I have to?
Simply stated, the C standard requires a compiler to initialize 
statically allocated variables to zero.  Consequently, if you define 
a variable outside of a function (or inside a function with the 
static attribute) it is guaranteed to be initialized to zero in the 
absence of an explicit initialization.  No such guarantee is made 
for dynamically allocated variables, i.e., those defined within a 
function but not having the static attribute.

Note that you can arrange for statically allocated variables to be 
uninitialized if you wish.  To do so, need to use the attribute 
__attribute__((section(".noinit"))).  This most conveniently done by 
defining a macro:

#define NO_INIT __attribute__((section(".noinit")))
...
int myUninitializedVar NO_INIT;

It used to be that the avr-gcc documentation recommended against 
explicit zero initialization of statically allocated variables, e.g.

int myVar = 0;

The reason for this recommendation was that the compiler treated 
such explicit zero initializations the same as explicit non-zero 
initializations, creating space in the initialization data area of 
Flash for the zero data.  Newer versions of avr-gcc detect explicit 
zero initialization and treat it the same as having specified no 
explicit initialization.  There is no longer a Flash size penalty 
for explicit zero initialization of variables.

Don Kinzer
ZBasic Microcontrollers
http://www.zbasic.net

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.