On Saturday, 8 April 2017 at 11:01:34 UTC, biocyberman wrote:
On Saturday, 8 April 2017 at 10:09:47 UTC, Mike Parker wrote:
T kroundup32(T)(T x) {
    pragma(inline, true);
    --(x);
    (x)|=(x)>>1;
    (x)|=(x)>>2;
    (x)|=(x)>>4;
    (x)|=(x)>>8;
    (x)|=(x)>>16;
    return ++(x);
}


I also came up with this:

import std.stdio;
pragma( inline, true ):
static int kroundup32( int x){
--(x);
writeln("X: ",x);
 (x)|=(x)>>1;
writeln("X: ",x);
 (x)|=(x)>>2;
writeln("X: ",x);
(x)|=(x)>>4;
writeln("X: ",x);
 (x)|=(x)>>8;
writeln("X: ",x);
 (x)|=(x)>>16;
writeln("X: ",x);
 ++(x);
writeln("X: ",x);

 return x;
}

int main(){
  int num = 31;
  num = kroundup32(num);
  writeln("Num:", num);
  return 0;
}

Is this way of using pragma the same as your way? I am still new to this so I want to understand more.

The ':' means that it applies to everything that follows it, so while it doesn't matters in this example if you had
pragma( inline, true ):
int kroundup32( int x) { ... }

auto someVeryLargeFunction( Args args)
{
    // ...
}

and then you used someVeryLargeFunction in a bunch of places then that would cause a lot of binary bloat.

And is it a good idea to do manipulate 'num' directly so I can omit 'return' and avoid re-assigning statement? That's what C version does.

if you want the the function to affect the variable use a 'ref' as in

 void kroundup32(T)(ref T x) {
     pragma(inline, true);
     --(x);
     (x)|=(x)>>1;
     (x)|=(x)>>2;
     (x)|=(x)>>4;
     (x)|=(x)>>8;
     (x)|=(x)>>16;
     return ++(x);
 }

 int main(){
   int num = 31;
   writeln("Before: ",num); // 31
   kroundup32(num);
   writeln("After: ", num);   //32
   return 0;
 }

is it a good idea? I would not think it is necessary.

As an aside the C version has parentheses around the "x" because it is a macro and it is substituted as text not symbolically, they are not needed in D.

Reply via email to