Problem with using && as shorthand for if

Ersin Er ersin.er at gmail.com
Fri Aug 20 13:14:47 PDT 2010


On Fri, Aug 20, 2010 at 23:06, div0 <div0 at sourceforge.net> 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.


Then the first code should not compile too. By the way here is what Andrei
wrote in his latest book for the expression a&&b:

"""
* If the type of b is not void, then the expression has type bool. If a is
nonzero, the
expression evaluates b and yields true if and only if b is nonzero.
Otherwise, the
expression evaluates to false.

* If b has type void, the expression has type void as well. If a is nonzero,
b is evaluated.
Otherwise, b is not evaluated.

Using && with a void expression on the right-hand side is useful as
shorthand for an
if statement:

string line;
...
line == "#\n" && writeln("Got a # successfully");
"""

So I expect my code to compile as well.


> --
> My enormous talent is exceeded only by my outrageous laziness.
> http://www.ssTk.co.uk
>



-- 
Ersin ER
http://metasolid.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d-learn/attachments/20100820/a50de6b8/attachment-0001.html>


More information about the Digitalmars-d-learn mailing list