Updated C Interoperability and Type Casting (markdown) authored by williamfgc's avatar williamfgc
<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 &lt;math.h&gt;
#include &lt;stdio.h&gt;
1. <strong>Avoid mixing C headers, functions, and casting</strong> use corresponding C++ equivalent. Example: use ```cmath``` not ```math.h```, ```iostream``` not ```stdio.h```
* _Don't_
``cpp
#include <stdio.h>
#include <math.h>
...
float powerOfTwo = powf( 2.f, 5.f );
printf ( &quot;2^5 = %f\n&quot;, powerOfTwo );</code></pre></li></ul></li><li><code>Do</code> Use C++ header/functions<ul><li><pre style="border: 0;"><code>#include &lt; cmath &gt;
#include &lt; iostream &gt;
printf( "2^5 = %f\n", powerOfTwo );
* _Do_
``cpp
#include <iostream>
#include <cmath>
...
constexpr float powerOfTwo = std::pow ( 2., 5. );
std::cout &lt;&lt; &quot;2^5 = &quot; &lt;&lt; powerOfTwo &lt;&lt; &quot;\n&quot;;
</code></pre></li></ul></li></ul></li>
constexpr float powerOfTwo = powf( 2.f, 5.f );
std::cout << "2^5 = " << powerOfTwo << "\n";
<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++ –&gt; C —&gt; Fortran </li><li>C++ –&gt; C —&gt; JNI —&gt; Java</li></ul></li></ul></li>
2. <strong>Exception for using C headers/functions:</strong>
* C++ API is deprecated or not fully supported libraries ( _e.g._ MPI, CUDA_C, PETSc )
* No POSIX equivalent in C++: _e.g._ ```unistd.h, shmem.h, sys/ipc.h```
* Language Interoperability through C
```
C++ --> C --> Fortran --> C --> C++
C++ --> C --> JNI --> Java --> JNI --> C --> C++
```
<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&lt; int &gt; ( foo );</code></pre></li></ul></li>
<ul><li><pre style="border: 0;"><code> reinterpret_cast&lt; double* &gt; ( foo );</code></pre></li></ul</li>
</ul></li></ol>
3. <strong>Avoid C-style casting:</strong> use C++11 style casting: ```static_cast, dynamic_cast, reinterpret_cast``.
* Don't
```cpp
int foo = ( int ) bar;
char* buffer = (char*) data;
```
* Do
```cpp
int foo = static_cast<int>( foo );
char* buffer = reinterpret_cast<char*>( data );
```
\ No newline at end of file