Topic: is variable declaration in if statement conditional
Author: =?ISO-8859-1?Q?Daniel_Kr=FCgler?= <daniel.kruegler@googlemail.com>
Date: Tue, 29 May 2012 22:19:56 -0700 (PDT)
Raw View
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
--
[ comp.std.c++ is moderated. To submit articles, try posting with your ]
[ newsreader. If that fails, use mailto:std-cpp-submit@vandevoorde.com ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]