Skip to content

C Interoperability and Type Casting

williamfgc edited this page May 4, 2017 · 7 revisions
  1. Avoid mixing C headers, functions, and casting use corresponding C++ equivalent. Example: use cmath not math.h, iostream not stdio.h

    • Don't

      #include <stdio.h>
      #include <math.h>
      ...
      float powerOfTwo = powf( 2.f, 5.f );
      printf( "2^5 = %f\n", powerOfTwo );
    • Do

      #include <iostream>
      #include <cmath>
      ...
      constexpr float powerOfTwo = powf( 2.f, 5.f );
      std::cout << "2^5 = " << powerOfTwo << "\n";              
  2. Exceptions for using C headers/functions:

    • C++ API is deprecated or not fully supported in 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++
      
  3. Avoid C-style casting: use C++11 style casting: static_cast, dynamic_cast (classes), reinterpret_cast.

    • Don't
         int foo = ( int ) bar;
         char* buffer = ( char* ) data;
    • Do
         int foo = static_cast<int>( foo );
         char* buffer = reinterpret_cast<char*>( data );