|
| 1 | +Typedef versus #define in C++ |
| 2 | + |
| 3 | +typedef: The typedef is used to give data type a new name. For example, |
| 4 | + |
| 5 | +COde: |
| 6 | + |
| 7 | +// C program to demonstrate typedef |
| 8 | +#include <stdio.h> |
| 9 | + |
| 10 | +// After this line BYTE can be used |
| 11 | +// in place of unsigned char |
| 12 | +typedef unsigned char BYTE; |
| 13 | + |
| 14 | +int main() |
| 15 | +{ |
| 16 | + BYTE b1, b2; |
| 17 | + b1 = 'c'; |
| 18 | + printf("%c ", b1); |
| 19 | + return 0; |
| 20 | +} |
| 21 | + |
| 22 | +Output: c |
| 23 | + |
| 24 | +Code: |
| 25 | + |
| 26 | +// C program to demonstrate #define |
| 27 | +#include <stdio.h> |
| 28 | + |
| 29 | +// After this line HYD is replaced by |
| 30 | +// "Hyderabad" |
| 31 | +#define HYD "Hyderabad" |
| 32 | + |
| 33 | +int main() |
| 34 | +{ |
| 35 | + printf("%s ", HYD); |
| 36 | + return 0; |
| 37 | +} |
| 38 | + |
| 39 | + |
| 40 | +Output: |
| 41 | +Hyderabad |
| 42 | + |
| 43 | + |
| 44 | +Difference between typedef and #define: |
| 45 | + |
| 46 | +1.typedef is limited to giving symbolic names to types only, whereas #define can be used to define an alias for values as well, e.g., 2.you can define 1 as ONE, 3.14 as PI, etc. |
| 47 | +3.typedef interpretation is performed by the compiler where #define statements are performed by preprocessor. |
| 48 | +4.#define should not be terminated with a semicolon, but typedef should be terminated with semicolon. |
| 49 | +5.#define will just copy-paste the definition values at the point of use, while typedef is the actual definition of a new type. |
| 50 | +6.typedef follows the scope rule which means if a new type is defined in a scope (inside a function), then the new type name will only 7.be visible till the scope is there. In case of #define, when preprocessor encounters #define, it replaces all the occurrences, after 8.that (No scope rule is followed). |
| 51 | + |
| 52 | + |
| 53 | +typedef char* ptr; |
| 54 | +ptr a, b, c; |
| 55 | + |
| 56 | +the statement effectively becomes |
| 57 | + |
| 58 | +char *a, *b, *c; |
| 59 | + |
| 60 | +This declares a, b, c as char*. |
| 61 | + |
| 62 | +In contrast, #define works like this: |
| 63 | + |
| 64 | +#define PTR char* |
| 65 | +PTR x, y, z; |
| 66 | + |
| 67 | +the statement effectively becomes |
| 68 | +char *x, y, z; |
| 69 | + |
| 70 | +This makes x, y and z different, as, x is pointer-to-a char, whereas, y and z are char variables. |
| 71 | + |
| 72 | + |
| 73 | +Conclusion: |
| 74 | + |
| 75 | +Use typedef to give data type a new name and use #define to define constant and other alias. |
| 76 | + |
| 77 | + |
| 78 | + |
0 commit comments