[prog] [C] strings bug

Jimen Ching jching at flex.com
Thu Apr 10 23:43:25 EST 2003


Is it a good idea to give incomplete answers to new programmers?

In ANSI C, uninitialized global variables and static local variables are
set to zero by the run-time environment before main() is entered.  And,
yes, there is a valid reason for using this default behavior.  The code:

	int i;
	int main() { static int j; return i + j; }

and the code

	int i = 0;
	int main() { static int j = 0; return i + j; }

will generate different executable images, but will behave the same when

Initialized global variables and initialized static local variables are
placed into a special section called the 'data' section in an executable
image.  For desktop applications, this doesn't really matter all that
much.  But for embedded systems, this matters a lot!!!

Uninitialized global variables, and uninitialized static local variables
are placed into a section also; called the 'bss' section.  And
instructions are placed into the 'code' section.  There are also other
sections that an executable may include.  It depends on the file format,
i.e. a.out, ELF, COFF, etc.

Of course, everyone already knows uninitialized automatic variables are
untouched when entering a function.  But initialized automatic variables
are set each time the function is entered.

In ANSI C++, POD (plain old data) types behave exactly like the built-in
types in C, as described above.  This is necessary for backwards
compatibility.  For classes and structures, the constructor and destructor
is always called, no matter how the variable is declared, i.e.
initialized, uninitialized, static, etc.  It doesn't matter.  In the case
of temporaries, only non-trivial constructors and destructors are called.
For example:

	struct X { X() { std::cout << "X()" << std::endl; } }
	int main() { X x; return 0; }

will output "X()" when run.  Also, concerning automatic variable
initializers; according to section 6.7 of the ISO/IEC 14882 and I qoute:

	It is possible to transfer into a block, but not in a way that
	bypasses declarations with initialization.  A program that jumps
	from a point where a local variable with automatic storage
	duration is not in scope to a point where it is in scope is ill-
	formed unless the variable has POD type and is declared without
	an initializer.

For you new programmers, I'll let you have fun interpreting this clause.
Anyone care to try providing an ill-formed and a well-formed C++ code
example that demonstrates the requirement in this clause?  ;-)

Jimen Ching (WH6BRR)      jching at flex.com     wh6brr at uhm.ampr.org

More information about the Programming mailing list