Path: ...!weretis.net!feeder8.news.weretis.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: on allowing "int a" definition everywhere Date: Thu, 22 Aug 2024 11:12:54 -0700 Organization: None to speak of Lines: 54 Message-ID: <87cym0h1eh.fsf@nosuchdomain.example.com> References: <87h6bchpzf.fsf@nosuchdomain.example.com> <87plq026li.fsf@bsb.me.uk> MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Thu, 22 Aug 2024 20:12:54 +0200 (CEST) Injection-Info: dont-email.me; posting-host="da918a99e4143e2bc1b37425b53bc125"; logging-data="566017"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+MbSm9AGnfHtClLelcSBJo" User-Agent: Gnus/5.13 (Gnus v5.13) Cancel-Lock: sha1:MalwpHbXmBt8UT6Kdnj01eH1mlQ= sha1:XRhpgJ5HcSD4HF4QtzItzmXiPWQ= Bytes: 3046 Ben Bacarisse writes: > Keith Thompson 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.com void Void(void) { Void(); } /* The recursive call of the void */