From mboxrd@z Thu Jan 1 00:00:00 1970 From: dexen deVries To: Fans of the OS Plan 9 from Bell Labs <9fans@9fans.net> Date: Thu, 8 Sep 2011 11:57:07 +0200 User-Agent: KMail/1.13.6 (Linux/3.1.0-rc5-l38+; KDE/4.5.5; x86_64; ; ) References: In-Reply-To: MIME-Version: 1.0 Content-Type: Text/Plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Message-Id: <201109081157.08110.dexen.devries@gmail.com> Subject: Re: [9fans] C question - completely OT, but I'd like to know the answer Topicbox-Message-UUID: 1bacee28-ead7-11e9-9d60-3106f5b1d025 On Thursday 08 of September 2011 11:41:05 Winston Kodogo wrote: > (...) > I'm puzzled as to why the line "int nigel =3D 1;" is syntactically OK, > and although it seems to have declared the variable "nigel" - else the > following code would fail to compile - has failed to give it the > initial value of 1, as requested. consider the `switch' statement a switchboard that jumps to one of the=20 `case's. nigel is not getting initialized because this code path is not executed -- = as=20 it is not part of any `case' taken by the switch.=20 an `automatic' (non-static) variable is initialized by a piece of code, the= =20 code gets executed whenever flow of control reaches that particular place. a static variable (`static int inigel =3D 1') is initialized by static data= ,=20 before any code gets executed -- and only once. static will do what you=20 expect. this is why you can place a static variable outside of any function and it= =20 still gets initialized. both kinds have their uses, in different situations. for reference: for (int i =3D 0; i < 8; ++i) { int nigel =3D 1; // this emits some code that gets executed for every loo= p and=20 resets the var to `1' printf("nigel: %d,", nigel); ++nigel; } will print: nigel: 1,nigel: 1,nigel: 1, ... on the other hand:=20 for (int i =3D 0; i < 8; ++i) { static int nigel =3D 1; // this var is initialized just once before main(= )=20 begins and doesn't reset printf("nigel: %d,", nigel); ++nigel; } will print: nigel: 1,nigel: 2,nigel: 3, ... =2D-=20 dexen deVries [[[=E2=86=93][=E2=86=92]]] =46or example, if the first thing in the file is: an XML parser will recognize that the document is stored in the traditional= =20 ROT13 encoding. (( Joe English, http://www.flightlab.com/~joe/sgml/faq-not.txt ))