Sujet : Re: on allowing "int a" definition everywhere
De : thiago.adams (at) *nospam* gmail.com (Thiago Adams)
Groupes : comp.lang.cDate : 22. Aug 2024, 12:10:34
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <va76ba$dljb$1@dont-email.me>
References : 1 2 3 4 5 6
User-Agent : Mozilla Thunderbird
On 22/08/2024 07:00, Bart wrote:
I assume the (...) tests the value of 'f'? If so then perhaps this is a shorter way of expressing the same thing:
{
FILE * f = fopen("file.txt", "r");
if (f) {
/* … */
fclose(f);
}
}
fwrite(f, …);
Yes, this is the equivalent code.
C++ allows two forms. One with explicit check and another one with implicit check.
if (FILE* f = fopen("file.txt", "r"); f) /*f is checked explicitly*/
{
/*...*/
fclose(f);
}
if (FILE* f = fopen("file.txt", "r")) /*f is checked implicitly*/
{
/*...*/
fclose(f);
}
I also have considered for cake to have a extra part that is "defer" part.
if (FILE* f = fopen("file.txt", "r"); f; fclose(f))
{
}
But if 'defer' were added to C2Y, we could then do the following:
if (FILE* f = fopen("file.txt", "r"); f; )
{
defer fclose(f);
/*...*/
}
Sometimes, too much syntactic sugar is not good because it creates too many variants.