Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

is variable declaration in if statement conditional expression allowed by standard?

116 views
Skip to first unread message

Brendan

unread,
May 29, 2012, 2:25:02 PM5/29/12
to
I didn't think it was, but recently I wrote this and was surprised
when it actually worked on my compiler (G++):

if (int err_code = some_function()) {
throw std::runtime_error(strerror(err_code));
}

Testing is seemed that err_code was scoped to the if statement in the
same way it would have been in a for loop.

Is this actually allowed by the standard, or is this just a GNU
extension?

Thanks,
Brendan Miller


--
[ comp.std.c++ is moderated. To submit articles, try posting with your ]
[ newsreader. If that fails, use mailto:std-cpp...@vandevoorde.com ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]

Daniel Krügler

unread,
May 30, 2012, 1:19:56 AM5/30/12
to
Am 29.05.2012 20:25, schrieb Brendan:
>
> I didn't think it was, but recently I wrote this and was surprised
> when it actually worked on my compiler (G++):
>
> if (int err_code = some_function()) {
> throw std::runtime_error(strerror(err_code));
> }
>
> Testing is seemed that err_code was scoped to the if statement in the
> same way it would have been in a for loop.
>
> Is this actually allowed by the standard, or is this just a GNU
> extension?


This is no extension, but valid C++03 and C++11. The grammar of the
if-selection statement used here is:

if ( condition ) statement

and /condition/ is defined as:

condition:
expression
type-specifier-seq declarator = assignment-expression

The second item corresponds to your example. The wording also
guarantees that the name introduced here (err_code) is local to the
if-statement.

HTH & Greetings from Bremen,

Daniel Krügler
0 new messages