Avoid Magic Numbers by using Enum in C/C++


Using Magic Numbers is one of the causes of ugly code. For example, if you want to deal with two protocols, HTTP and FTP (to count the data packages), you can have two variables:

1
2
int nHttp = 0;
int nFtp = 0;
int nHttp = 0;
int nFtp = 0;

Now, later, if you want to add SMTP and SSH, you continue the declaration:

1
2
3
4
int nHttp = 0;
int nFtp = 0;
int nSmtp = 0;
int nSsh = 0;
int nHttp = 0;
int nFtp = 0;
int nSmtp = 0;
int nSsh = 0;

You would need to deal four times (e.g. printf, assert) when it comes to the protocols. A better solution is to use array:

1
2
3
4
5
int nProto[4];
// nProto[0] = HTTP
// nProto[1] = FTP
// nProto[2] = SMTP
// nProto[3] = SSH
int nProto[4];
// nProto[0] = HTTP
// nProto[1] = FTP
// nProto[2] = SMTP
// nProto[3] = SSH

Wow, you can start using Loops, but the magic number comes if you, for example, want to get the SMTP number, which is nProto[2]. This is Magic Number. This is bad, if you change the sequence of the elements in the array. It is error-prone.

Now, a better solution is to use enum in C/C++ for better code readability.

1
2
3
4
5
6
7
enum PROTO{  
  PROTO_HTTP,  
  PROTO_FTP,  
  PROTO_SMTP,  
  PROTO_SSH
};
int nProto[4];
enum PROTO{  
  PROTO_HTTP,  
  PROTO_FTP,  
  PROTO_SMTP,  
  PROTO_SSH
};
int nProto[4];

We can then use nProto[PROTO_SMTP] for better code readability. If you add more elements in the array, you would just need to update the enum, without need to adjust the existing code.

You would still need to update the magic number “4”, which can be completed removed by:

1
2
3
4
5
6
7
8
enum PROTO{  
   PROTO_HTTP,  
   PROTO_FTP,  
   PROTO_SMTP,  
   PROTO_SSH,  
   PROTO_NUM /* Total Number of Protocols */
};
int nProto[PROTO_NUM];
enum PROTO{  
   PROTO_HTTP,  
   PROTO_FTP,  
   PROTO_SMTP,  
   PROTO_SSH,  
   PROTO_NUM /* Total Number of Protocols */
};
int nProto[PROTO_NUM];

This is just awesome, just keep adding more protocols and you don’t need to change any ‘magic number’ but ensure that the PROTO_NUM is placed at the last element of the enum.

enum and array work for both C and C++, but in C++, you can use STL container:

1
std::vector<int> nProto(PROTO_NUM);
std::vector<int> nProto(PROTO_NUM);

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
389 words
Last Post: Disable WordPress Maintenance Mode when Upgrading Plugins Stuck
Next Post: SQL Coding Exercise - Employees Earning More Than Their Managers

The Permanent URL is: Avoid Magic Numbers by using Enum in C/C++

Leave a Reply