Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use #define or constant char/int?

In general, is it better to define some specific parameters (e.g. (char *) UserIPaddr="192.168.0.5" , (int) MAX_BUF=1024) by #define or constant char */ int?

I read some threads say that it is better not to use #define when it is possible. However, I see quite common usage of #define on open source codes one example from a source code:

#define IEEE80211_WLAN_HDR_LEN      24
    a_uint8_t *iv = NULL;
    a_uint16_t tmp;
    a_uint16_t offset = IEEE80211_WLAN_HDR_LEN;

#define could be avoided to use there, but I wonder why it was preferred to use #define on that case for example. How should I decide when to use #define or not?

like image 604
Johan Elmander Avatar asked Jun 29 '13 13:06

Johan Elmander


2 Answers

In C const declarations do not produce constant expressions, So if you need to have a constant expression its not possible using const, the traditional and more commonly used way to do so is using # define.

For example const int cannot be used in:

  • a case label or
  • as a bit-field width or
  • as array size in a non-VLA array declaration (pre C99 days)
like image 83
Alok Save Avatar answered Nov 02 '22 10:11

Alok Save


There are few reasons to use #define. There is little it accomplishes that a static const or enum cannot.

As Alok Save mentions, static const int cannot produce an integral constant expression in C (I'm not double checking the C standard; it isn't the case in C++ though). But enum can do that. However enum in pure C does not grow to accommodate values larger than INT_MAX. So if you need a long value to use as an array bound or case label, #define is your friend. Or consider switching to using the C subset of C++, which doesn't have such restrictions.

like image 26
Potatoswatter Avatar answered Nov 02 '22 09:11

Potatoswatter