Problem with using && as shorthand for if

Jonathan M Davis jmdavisprog at gmail.com
Fri Aug 20 13:16:33 PDT 2010


On Friday, August 20, 2010 13:06:11 div0 wrote:
> On 20/08/2010 20:59, Ersin Er wrote:
> > Hi,
> > 
> > The following code compiles and outputs "1 = 1" as expected:
> > 
> > 1 == 1&&  writeln("1 = 1");
> > 
> > However, the following code fails to compile (although it should not):
> > 
> > 1 == 2&&  writeln("1 = 2");
> > 
> > The error is as follows:
> > 
> > Error: integral constant must be scalar type, not void
> > 
> > What I expect that the second code should also compile and output nothing
> > when executed.
> > 
> > Am I missing something?
> > 
> > Thanks.
> 
> The return type of writeln is void.
> You can't && with void.
> 
> You are asking
> 
> 'is X true AND <something which can't return true or false> is true'
> 
> which is clearly nonesense.

It's legal according to TDPL. It seems to be intended to be used as a shorthand 
for if. So, stuff like

condition && writeln("my output");

are supposed to be perfectly legal as bizarre as that may seem. I don't believe 
that it would be legal to do

if(condition && writeln("my output"))
{
}

since the result fed to if must be a bool, but a statement doesn't need to 
result in bool, so apparently you can use && with a void function in a 
statement. It's just that the void function must be last.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list