When to use #define or char / int constant?

In general, is it better to define some specific parameters (for example, (char *) UserIPaddr="192.168.0.5" , (int) MAX_BUF=1024 ) with #define or constant char */ int ?

I read several threads saying that it is better not to use #define when possible. However, I see a fairly common use of #define in open source, one example from the 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 used, but I wonder why it was preferable to use #define in this case, for example. How do I decide when to use #define or not?

+6
source share
3 answers

C const declarations do not produce constant expressions. Therefore, if you need to have a constant expression, then this is not possible when using const , the traditional and most often used way to do this is to use # define .

For example, const int cannot be used in:

  • case label or
  • as the width of the bit field or
  • as the size of an array in a non-VLA array declaration (up to C99 days)
+7
source

There are several reasons to use #define . It does little that static const or enum cannot.

As Alok Save mentions, static const int cannot create an integral constant expression in C (I do not check the double standard of C, but this is not the case in C ++). But enum can do this. However, enum in pure C does not grow to accommodate values ​​larger than INT_MAX . Therefore, if you need to use the long value to use as an array binding or label label, #define is your friend. Or switch to using a subset of C in C ++, which does not have such restrictions.

+3
source

My rule is to not use #define unless the character should be a compile-time constant. With that in mind, I personally would not use #define in your example.

To select another example from the same source file :

 #define CRYPTO_KEY_TYPE_AES 2 ... switch (keytype) { case CRYPTO_KEY_TYPE_AES: 

Here CRYPTO_KEY_TYPE_AES must be a constant expression, and therefore the use of a constant variable will not be performed.

+2
source

Source: https://habr.com/ru/post/948379/


All Articles