Sujet : Re: on allowing "int a" definition everywhere
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 22. Aug 2024, 19:12:54
Autres entêtes
Organisation : None to speak of
Message-ID : <87cym0h1eh.fsf@nosuchdomain.example.com>
References : 1 2 3 4 5 6 7
User-Agent : Gnus/5.13 (Gnus v5.13)
Ben Bacarisse <
ben@bsb.me.uk> writes:
Keith Thompson <Keith.S.Thompson+u@gmail.com> writes:
The original code:
>
if (FILE* f = fopen("file.txt", "r"))
>
I think the proposal would be a declaration to precede an expression:
>
if (FILE* f = fopen("file.txt", "r"); f)
I don't think so, or at least I don't think it's only that.
In C++17, the syntax for an if statement is (leaving some stuff out):
if ( init-statement[opt] condition ) statement
where an init-statement is an expression statement or a simple
declaration (which includes a trailing semicolon), and a condition is an
expression or a declarator with an initialization. So these are
equivalent in C++:
if (FILE* f = fopen("file.txt", "r"))
if (FILE* f = fopen("file.txt", "r"); f)
{
/*...*/ fclose(f);
}
>
doesn't allow for taking some non-trivial action of the fopen() call
fails, but if a declaration in an if condition is visible in the else
clause, you could write something like:
>
if (FILE* f = fopen("file.txt", "r")) {
/*...*/
fclose(f);
}
else {
perror("file.txt");
exit(EXIT_FAILURE); // or try something else
}
>
What's the significance of the declared name being in scope in the else
clause here?
My brain seems to have taken a detour while I was writing that.
fopen() returns either a valid pointer or NULL; if it fails, there's no
extra information in the pointer itself. But if a function's result on
failure includes information about how it failed, accessing the value in
the else clause is useful. (And C++ supports this.)
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */