top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

C: Enum constant or Macro constant, when to use which one ?

0 votes
1,094 views
C: Enum constant or Macro constant, when to use which one ?
posted Aug 14, 2014 by Harshita

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

It is totally use choice, Some may prefer one or the other for stylistic reasons, but before making any choice where to use " enum " and where " macro" plz keep these in mind.

  1. It is best to use enums when some variable can hold one of multiple values which can be given names.
    for example. (color, day, months etc)
    enum color {
    RED,
    BLUE,
    YELLOW,
    // etc
    };

  2. You can use macro where you doing same set of things again an again.
    for example .
    debug prints. for that just define a macro for the debug print and use.
    some constant value.
    int buff [ MAX_LEN ] // define MAX_LEN as a macro.

  3. One difference is that macros allow you to control the integral type of related constants. But an enum will use an int.
    ie.
    #define X 100L
    enum { Y = 100L };

     printf("%ld\n", X);
     printf("%d\n", Y);       /* Y has int type */
    
  4. Macro is a preprocessor where as enum is not.

answer Aug 14, 2014 by Arshad Khan
Thanks for the correction. :)
MACRO is NOT a preprocessor. #"define" is a  preprocessor directive.  MACRONAME is replaced by MACROBODY at the preprocessor stage of compilation.
Thanks for the correction.
Ya you are right MACRO is get preprocessed. and it is replaced by the contents of the macro.
Similar Questions
0 votes
#define MY_STRUCT
typedef struct{ 
...
... 
} my_struct;

Above code is giving me error (MY_STRUCT) is not working as expected, Looks that some silly mistake, please point out as I have wasted many hours?

Sorry for hiding my identity?

...