Home > Blogs > The C++ Features I Like Most Series: typedef and sizeof

The C++ Features I Like Most Series: typedef and sizeof

By  Sep 27, 2009

Topics: Programming, C/C++

Operator sizeof and typedef are among the first features that new language designers omit from their new born baby with curly braces to make a point: "this isn't yet another C++ clone". We're lucky to have them in C and C++, though.

Typedef is usually criticized as being a source of confusion because it allows programmers to disguise built-in types. However, in a programming language that doesn't guarantee a portable binary representation of its built-in data types, typedef enables you to bridge layout incompatibilities. Typedef is also useful for hiding indecipherable syntactic monsters such as a pointer to a function that returns another pointer to function. The claim that typedef obscures code is outdated and conservative because almost every high-level programming language allows programmers to define "abstract data types". Ada and Pascal are two fine examples. In C you have one more reason for using typedef -- avoiding the repetitive use of the keywords struct, union and enum before the type name.

There's no need to explain why sizeof is essential but you often find yourself wondering how other languages with curly braces get by without it. The truth is that they cheat. They don't have an overt sizeof operator but they do have built-in arrays that can report their size, and classes that represent byte arrays with similar facilities. In some problematic cases (and languages) programmers resort to assembly programming to determine the size of an object. All these workarounds are significantly inferior compared to an overt, compile-time operator that the language supports directly -- operator sizeof for example.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Inside Java SE 9

Inside Java SE 9