C11's ease of use and how it compares with C++ - Embedded.com

C11’s ease of use and how it compares with C++


The 2011 revision of the ISO standard for C (dubbed “C11”) provides several ease-of-use features, most of which are compatible with C++11. In order to use the normal-looking names I'll show here, you need to include these headers: , , , , , , , and .


C11 and C++11 both provide new syntax for specifying alignment. The expression alignof(type-name ) designates the alignment of type-name ; it is a constant expression, as is the familiar sizeof(type-name ) . (There's one exception in C: Applying sizeof to a variable length array, or VLA, produces a non-constant expression.) The expression alignof(char) is, of course, always 1.

There is a similar syntax for declarations:

   int alignas(double) b;

specifies that b is an int , but is aligned suitably for a double . Or for a more realistic example,

alignas(double) unsigned char buf[sizeof(double)]; 

specifies that buf is an array of unsigned char , whose size and alignment would be suitable to hold a double .

Alignment can be specified as an integer: alignas(constant-expression ) specifies the constant-expression as an alignment. Thus, alignas(type-name ) means the same thing as alignas(alignof(type-name )) .

For each target platform, there is some type that has the largest alignment requirement; that type can be named by the typedef max_align_t , so a declaration that specifies alignas(max_align_t) requests an alignment that will be suitable for any type on that platform. If a program requests an alignment that is greater than alignof(max_align_t) , the program is not portable because support for an over-aligned type is optional.

The C11 library provides aligned_alloc(size_t bound, size_t nbytes) , which allocates nbytes of storage aligned on a bound boundary. The most common use case heard by the committee was to request a buffer aligned on a cache boundary (typically 32k or 64k); however, you have to check your own compiler's manual because the implementation gets to determine the valid alignments.

To read more of this external content, go to “C's New Ease of Use and How the Language Compares with C++ ,” on Dr. Dobbs.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.