Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #67112

Re: Observing the if-scope(s)

From Keith Thompson <kst-u@mib.org>
Newsgroups comp.lang.c
Subject Re: Observing the if-scope(s)
Date 2015-08-11 08:28 -0700
Organization None to speak of
Message-ID <lnoaiddeu6.fsf@kst-u.example.com> (permalink)
References <if-20150811153808@ram.dialup.fu-berlin.de>

Show all headers | View raw


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 <stdio.h>
>
> 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 <stdio.h>
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  <http://www.ghoti.net/~kst>
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"

Back to comp.lang.c | Previous | Next | Find similar | Unroll thread


Thread

Re: Observing the if-scope(s) Keith Thompson <kst-u@mib.org> - 2015-08-11 08:28 -0700

csiph-web