Monday, January 18, 2016

Little Known C Language "Feature"s

There are several useful "feature"s in C language which are not widely known. Only those digging deep enough to C libraries or kernel code knows these "feature"s. These are some of them:
  • The C offsetof() macro. In many cases, this macro is utilized to help implement a sort of object oriented relationship (akin to sub-class<-->super-class in C++) between related C structures (or object if you prefer). You can use it to "obtain" pointer to the super-class given pointer to the sub-class and vice versa. Some useful explanation about this feature: Offsetof (Wikipedia), Greg KH explanation on offsetof in Linux Kernel code. Anyway, in some cases you can use compiler extension (built-ins) to achieve the same effect. In GCC there is __builtin_offsetof built-in that you can use. In fact, offsetof() translates to __builtin_offsetof in GCC.
  • const keyword can be used to designated input and output arguments in C/C++ function. You can use this keyword to force the compiler to notify you or outright balked out of compilation when some code inadvertently change the value of a function argument designated as const. Basically, you use it to enforce whether the function can modify the argument or not. An argument which strictly used as input (in a sense, must not be modified) can be designated as such with const. This is an excellent writeup on the matter: The C++ 'const' Declaration: Why & How.
  • Pointer aliasing issue, i.e. a situation where more than one pointer refer to the same object. Understanding this "feature" is important when you want to write high-performance C/C++ code. It's a quite complicated but important matter because it gives you the capability to "tell" the C/C++ compiler about your intention and avoid expensive memory accesses. See:
I think knowing these "feature"s is critical to create high quality and high performance C/C++ code.
Post a Comment

No comments: