Utility - Displaying in an user understandable string format for the given input

This is again an interesting one for better optimization and comprehension!! 

For an instance, if your array or variable stores some random values but each depicts some meaning, it will not be good to display it randomly. 


#include <stdio.h>

/* Enums are easy to handle than #define in this context */
#if 0 
#define MODULE_TRUE 1
#define MODULE_FALSE 0
#define MODULE_MAX 2
#endif

/* 
 * Explicitly numbering is my choice
 * as it avoids unnecessary hurdles
 */
enum {
   MODULE_FALSE = 0, 
   MODULE_TRUE = 1,
   MODULE_MAX = 2
};

const char *prefer[MODULE_MAX + 1] = 
{
   "Secondary/Guest",
   "Primary/Sudo",
   "Invalid",
};

void main()
{
    int access = MODULE_FALSE;
    printf("The Access Preference is %s\n", prefer[access]);
    access = MODULE_TRUE;
    printf("The Access Preference is %s\n", prefer[access]);
    return;
}

 

The Access Preference is Secondary/Guest
The Access Preference is Primary/Sudo


Anyway we need to define the random numbers in user-understandable meaningful name, and there is no short-cut ;-) 

Here is an another program which prints the value of constants which was defined using #define in C++


#include <iostream>
using namespace std;

#define STR(X) #X 
#define SOME_TEXT(x) cout << #x << " " << STR(x) << endl
#define ONLY_MSG(x) cout << STR(x) << " "

#define HELLO_TEXT Shirley 
#define NUMBER 1
#define PREFERENCES prefers programming at
#define CLOCK 12.30

int main() 
{
    SOME_TEXT(HELLO_TEXT);
    SOME_TEXT(NUMBER);
    SOME_TEXT(PREFERENCES);
    SOME_TEXT(CLOCK);

    ONLY_MSG(HELLO_TEXT);
    ONLY_MSG(NUMBER);
    ONLY_MSG(PREFERENCES);
    ONLY_MSG(CLOCK);

    return 1;
}


Output:

1
2
3
4
5
HELLO_TEXT Shirley
NUMBER 1
PREFERENCES prefers programming at
CLOCK 12.30
Shirley 1 prefers programming at 12.30 

Hope this helps!! 


Comments