Wednesday, 23 January 2019

Which is better typedef or #define and Why

Which is better typedef or #define? Why?

Answer:


The #define statement is a preprocessor statement. The preprocessor uses a differen t
syntax from the C++ language. Therefore using #define prevents the C++ compiler from
doing syntax checking on the statement.
C++ knows about typedef statements and can check them to make sure their syntax is
correct. Also consider the following:
#define CHAR_PTR char *
typedef char *char_ptr;
CHAR_PTR ptr1, ptr2;
char_ptr ptr3, ptr4;
This obviously declares four pointer variables. Unfortunately, the obvious is wrong. The
variable “ptr2” is a character, not a character pointer. That’s because the line it is
declared, when expanded, look like:
char * ptr2, ptr2;

No comments:

Post a Comment