Click here to Skip to main content
15,884,057 members
Articles / Desktop Programming / Win32
Tip/Trick

Gems for typedef and namespace in C

Rate me:
Please Sign up or sign in to vote.
4.72/5 (11 votes)
10 Mar 2017CPOL3 min read 20.6K   16   4
Gems for typedef and namespace in C

Introduction

Now is a good time to review the concept on struct, enum, union and namespace in C language. If you have feedback or comments, please provide them. Thank you.

To save time, many examples are classical and taken from [1] or [2]. I do not re-invent the wheel.

Quick Check

Can you interpret the following statement correctly?

typedef int *ptr, (*func)(), arr[5];

If you cannot interpret 100% correctly, please read on.

Namespace in C

There are multiple namespaces in C[1]:

  • label names
  • tags (one namespace for all structs, enums and unions)
  • member names (each struct or union has its own namespace)
  • everything else

Within a namespace, every identifer must be unique. An identical identifier can be applied to things in different namespaces. Because each struct or union has its own namespace, the same member names can be re-used in many different structs.

The following example is valid:

C++
// example 1
// all foos belong to different namespaces.
// what does it mean? sizeof(foo)?

struct foo {int foo;} foo;

typedef with Function Pointer

A classic example is the signal() prototype. The ANSI standard shows that signal is declared as:

C++
void (*signal(int sig, void (*func)(int) ) (int);

If we use typedef, we can simplify this declaration:

C++
typedef void (*ptr_to_func) (int);

//original declaration will be:
ptr_to_func signal(int, ptr_to_func);

So we refactor this complicated statement by factoring out the common piece. In a further way, we can simplify our legacy code.

typedef with type struct, enum, and union

Please see if this example is confusing?

C++
//example 2
//what are the differences among these blahh?
typedef struct blahh {int blahh; } blahh;
        struct blahh var1;
               blahh var2;

The take-away is: do not mess typedef only with structs; We can use typdef for the types that combine arrays, structs, pointers, or functions; use typedef for portable types; use typedef for casts to simplify the complicated type cast.

As for enum type, it is only a simple way to associate a series of names with a series of integer values. Another angle to say is: if a variable has a fixed set of values, then it is good to declare it enum type. C is a weakly typed language and enum type only provides very little that can't be done with #define. The definition is below:

enum optional_tag {a list of identifers} optional_variable_defintions;

Compared with #define, enum type has one advantage: #define names are typically discarded during compilation and enum names usually persist through to the debugger and can be used while debugging your code in IDE such as Visual Studio.

#define vs. typedef

We know there is a key difference between typedef and #define. I found a better way to express it. A typedef is a complete "encapsulated" type (you cannot add to it after you declare it)[1]. #define is a text replacement on the spot and it happens in pre-processing stage in compiling.

Please review the following two examples and see how much you can understand it:

C++
/* example 3   */
/* do you see difference ? */
#define fruit int
unsigned fruit i; /* legal */

typedef int fig;
unsigned fig i; /* illegal */
C++
/*  example 4     */
/* do you see difference ? */
#define int_ptr int *
int_ptr tiger, cat;

typedef char* char_ptr;
char_ptr saga, novel;

One Use Case of #define

#define can be used to simplify convoluted statement too. Here, it is the example:

C++
/* it is hard to remember */
enum type_tag { IDENTIFIER, QUALIFIER, TYPE };
if ( !strcmp(s, "volatile") ) return QUALIFIER;
C++
/* use trick to simplify the above example*/
#define STRCMP(a, R, b) (strcmp(a,b) R 0)
if ( STRCMP(s, ==, "volatile")) return QUALIFIER;

Points of Interest

If you understand these concepts better, you will be more confident to use C. If you get the essence of this article, [3] is the next article to go through.

References

  1. Expert C Programming: Deep C Secrets 1st Edition
  2. Why doesn't ANSI C have namespaces?
  3. Improve Code Clarity with Typedef
  4. typedef struct vs struct definitions [duplicate]
  5. Why should we typedef a struct so often in C?
  6. typedef
  7. C Preprocessor tricks, tips, and idioms
  8. The C Preprocessor
  9. C Programming Tips And Tricks For Beginners – Top 15
  10. C Programming Tips
  11. C Pre-Processor Magic
  12. The C Preprocessor
  13. C Macro Tips and Tricks
  14. Easy way to use variables of enum types as string in C?
  15. Assorted C/C++ tips and tricks.
  16. Recommended C Style and Coding Standards
  17. Don’t Follow These 5 Dangerous Coding Standard Rules
  18. C# Fundamentals: The Joys and Pitfalls of Enums
  19. 2 Rookie Java Constants and Enums Pitfalls

History

  • 27th February, 2017: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
turns good thoughts into actions...


Comments and Discussions

 
QuestionFunction Pointer Declaration Pin
RAMASWAMY EKAMBARAM6-Mar-17 19:10
professionalRAMASWAMY EKAMBARAM6-Mar-17 19:10 
AnswerRe: Function Pointer Declaration Pin
Southmountain10-Mar-17 7:05
Southmountain10-Mar-17 7:05 
PraiseMy vote of 5 Pin
VISWESWARAN19982-Mar-17 8:25
professionalVISWESWARAN19982-Mar-17 8:25 
GeneralRe: My vote of 5 Pin
Southmountain3-Mar-17 11:40
Southmountain3-Mar-17 11:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.