Path: csiph.com!eternal-september.org!feeder.eternal-september.org!mx02.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: Observing the if-scope(s) Date: Tue, 11 Aug 2015 08:28:33 -0700 Organization: None to speak of Lines: 51 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Injection-Info: mx02.eternal-september.org; posting-host="945944de09706c9b4e29b53c9d2efdc2"; logging-data="22020"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1/za5+C/d53CXefQkNNXtyD" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:9/ZFr2WZdA04PbGPdSwKMcnjocI= sha1:JSjeerZVWt0fBkPynSCkj9i/ZNc= Xref: csiph.com comp.lang.c:67112 ram@zedat.fu-berlin.de (Stefan Ram) writes: > An if-statement has two blocks and corresponding scopes. > > Can I observe this? > > For example, the following attemps are /not/ possible! > > #include > > int main( void ) > { int i = 1; > if( 1 )int i = 2; > if( int i = 3 ); > printf( "%d\n", i ); } > > One cannot use a declaration as a statement in > »if( 1 )int i = 2;« and one cannot use a declaration > as an expression in »if( int i = 3 );«. > > Can one observe that the if statement has its own > scope(s)? A compound literal that appears inside a function body creates an object that has automatic storage duration associated with the enclosing block. #include int main(void) { int *ptr1, *ptr2; ptr1 = &(int){1}; if (1) ptr2 = &(int){2}; printf("*ptr1 = %d\n", *ptr1); printf("*ptr2 = %d\n", *ptr2); } The first printf call prints the value of an int object whose lifetime ends at the closing "}" of the main function. The second has undefined behavior, since it prints the value of an object whose lifetime ends at the end of the if statement. On my system it prints *ptr1 = 1 *ptr2 = 2 and I'd be surprised if it behaved differently on another system, so we can't necessarily directly *observe* it. Such are the vagaries of undefined behavior. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"