Last Updated: February 25, 2016
·
677
· hagemt

Constant Redirections

If you ever (re?)use a number or string in your code, don't do this:

char buffer[4096];
...
snprintf(buffer, 4096, "%s/.%s/%s",
  path, argv[0], "v1.0");
...

Instead, use the tools you have available! Refer to the value by a name instead of using the constant itself. That way, if you ever want to change the value, it's an easy one-liner. (It also protects you from forgetting to update every usage, and prevents accidental edits when values collide. It also helps to keep all your definitions in one place!)

#define BUFFER_SIZE 4096
#define PRODUCT_NAME "program"
#define VERSION_STRING "v0.1"

char buffer[BUFFER_SIZE];
...
snprintf(buffer, BUFFER_SIZE, "%s/.%s/%s",
  path, PRODUCT_NAME, VERSION_STRING);
...