[OT] Converting booleans to numbers

Timon Gehr timon.gehr at gmx.ch
Thu Sep 21 15:06:06 UTC 2017


On 20.09.2017 23:13, nkm1 wrote:
> 
>> Example of a good use:
>>
>> void floodFill(dchar[][] data,dchar c,int i,int j) {
>>     void dfs(int a, int b) {
>> Example of a good use:
>>
>> void floodFill(dchar[][] data,dchar c,int i,int j) {
>>     void dfs(int a, int b) {
>>         if (a<0 || a >= data.length) return;
>>         if (b<0 || b >= data[a].length) return;
>>         if (data[a][b] == c) return;
>>         data[a][b] = c;
>>         foreach(i; 0 .. 4){
>>             dfs(a + (i==0) - (i==1),
>>                 b + (i==2) - (i==3));
>>         }
>>     }
>>     dfs(i, j);
>> }
> 
> I don't agree it's a good use.

Well, you can trust me that it is. ;)

> Actually, that seems quite obfuscated to me.

It's actually straightforward. This C code is obfuscated:

#define C ,
#define S(X) "Fizz"X"Buzz"
int main(){
   char j[]="00",*k=j+1,*g[]={k,S(C),S()};
   while(':'-*j)
     ++*k>'9'&&++*j&&(1<:*g=j:>='0'),
     puts(g[!((*j+*k)%3)|2*(3==*k%5)]);
   return 0;
}

(And yet, you are probably able to guess what it does.)

> Consider:

(I had considered that.)

> foreach (point; [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
>     dfs(a + point[0], b + point[1]);
> }

void floodFill(dchar[][] data,dchar c,int i,int j) @nogc {

I.e., I'd possibly call this a bad use of array literals. ;)
(The fix is to initialize a static array of static arrays.)

Also, it's not really a point, rather, it's a delta.

> Finds some random 10 programmers and ask them what's easier to understand...

Personally, I think it is a tie as both are obvious.

> Also, in my experience (in C and C++) it is extremely rare for programmers to use booleans in arithmetic. So even if in some situation you would have to replace this thing with more verbose (i == 0 ? 1 : 0), it's no big deal.

I didn't say it was.

> OTOH, booleans being numbers is a source of some bugs (just like other cases of weak typing). Not a ton of bugs, but the utility of implicit conversion to numbers is so unnoticeable that I'm sure it's just not worth it. 

So am I, but I wasn't commenting on trade-offs, only the view that there 
are no good uses.


More information about the Digitalmars-d-learn mailing list