[cctbxbb] Idiot C++ question

Luc Bourhis luc_j_bourhis at mac.com
Tue May 15 03:38:26 PDT 2012


Hi Phil,

> Looking at some cctbx C++ code, I note use of syntax like
> 
> int i = 1234;
> double d = static_cast<double>(i);
> 
> How is this different or indeed preferable to
> 
> double d = double(i);
> 
> or
> 
> d = i;
> 
> ?


Short answer: For conversions between non-pointer types, it does not matter but for pointer types, static_cast shall always be used to the exclusion of any other conversion.

The language lawyer:

The construct

double d = double(i)

which is known as functional-style cast is completely equivalent to the so-call cast notation, which comes from C:

double d = (double)i

You may see both in a few places in the cctbx code actually. 

The problem with those two constructs is that the compiler will let use convert a pointer to anything into a pointer to anything else. Consider:

#include <iostream>

struct foo { 
  int i,j; 
  foo(int i, int j): i(i), j(j) {} 
};

struct bar { 
  double d; 
  bar(double d): d(d) {} 
};

int main() {
  foo x(1, 2);
  bar *y = (bar *)&x;
  std::cout << y->d << std::endl;
  return 0;
}

This prints 4.24399e-314 on my computer but this depends on the compiler. On the contrary,

bar *y = static_cast<bar *>(&x)

is not legit and the compiler will bug you.

HtH,

Luc






More information about the cctbxbb mailing list