The do’s and don’ts of typedefs

Typedefs can be used to enhance portability by hiding the underlying type of an more abstract entity. For instance, when maximal precision of a floating point is required, one type can be used universally although its underlying representation is machine-dependent:

  	#ifdef  MAX_EIGHT_BYTE_FLOATtypedef  double astronomicalUnit; //on this machine 8 bytes is the maximal precision for a float#elsetypedef long double astromonicalUnit //this machine can store the largest float in 10 bytes.#endif

Typedefs can also improve readability by hiding complicated syntactic constructs such as pointers to functions or pointers to class members.On the other hand, excessive use of unnecessary typedefs can result in a less readable code and longer compilation time. Therefore, it should be used wisely. Mind that a typedef does not introduce a new type; it’s merely a synonym for an existing one, so the following sample will not compile:

 typedef unsigned long int * ULP;void f(unsigned long int * p) {/*..*/}void f(ULP p) {/*..*/} //error; redefinition of  f
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: