|
|
<p><strong>Avoid mixing C headers, functions, and casting if there is a corresponding C++ equivalent</strong></p><ol><li><strong>C Header/Function:</strong> use C++ equivalents. Use cmath not math.h, iostream not stdio.h <ul><li><code>Don't</code> Use C header/functions<ul><li><pre style="border: 0;"><code>#include <math.h>
|
|
|
#include <stdio.h>
|
|
|
...
|
|
|
float powerOfTwo = powf( 2.f, 5.f );
|
|
|
printf ( "2^5 = %f\n", powerOfTwo );</code></pre></li></ul></li><li><code>Do</code> Use C++ header/functions<ul><li><pre style="border: 0;"><code>#include < cmath >
|
|
|
#include < iostream >
|
|
|
...
|
|
|
constexpr float powerOfTwo = std::pow ( 2., 5. );
|
|
|
std::cout << "2^5 = " << powerOfTwo << "\n";
|
|
|
</code></pre></li></ul></li></ul></li>
|
|
|
|
|
|
<li><strong>Use C headers/functions when:</strong>
|
|
|
<ul><li>There is no C++ equivalent
|
|
|
<ul><li>C++ API is deprecated or not fully supported libraries ( <em>e.g.</em> MPI, CUDA_C, PETSc )</li><li>POSIX functionality <em>e.g.</em> unistd.h </li></ul></li><li>Language Interoperability is required
|
|
|
<ul><li>C++ –> C —> Fortran </li><li>C++ –> C —> JNI —> Java</li></ul></li></ul></li>
|
|
|
|
|
|
<li><strong>Type Casting:</strong> use C++11 style casting: static_cast, dynamic_cast, reinterpret_cast when corresponding instead of ( Type ) C style.<ul><li><code>Don't</code> <ul><li><pre style="border: 0;"><code> ( int ) foo;</code></pre></li></ul></li><li><code>Do</code>
|
|
|
<ul><li><pre style="border: 0;"><code> static_cast< int > ( foo );</code></pre></li></ul></li>
|
|
|
<ul><li><pre style="border: 0;"><code> reinterpret_cast< double* > ( foo );</code></pre></li></ul</li>
|
|
|
</ul></li></ol> |