LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   micro use in printf (https://www.linuxquestions.org/questions/programming-9/micro-use-in-printf-929405/)

gourav87 02-15-2012 01:01 AM

micro use in printf
 
#define WHITE BLACK

printf("WHITE");

is there any to print this output as-- BLACK.

this code i am using is in C.
Need urgent.
Thanks

Dark_Helmet 02-15-2012 01:12 AM

You will have to change the code some.

Code:

#define WHITE    "BLACK"

...

printf( WHITE );

To my knowledge, there's no way to have the cpp modify the contents inside a string literal. That is, after all, the whole point. The programmer wants the literal text between the double quotes.

Nominal Animal 02-15-2012 05:57 AM

An alternative:
Code:

#include <stdio.h>
#include <string.h>

#define MACRO(str) (strcmp((str), "WHITE") ? (str) : "BLACK")

int main(void)
{
    printf( MACRO("WHITE") );
    printf("\n");
    return 0;
}

This kind of string substitution is used by e.g. the gettext() package, for internationalization. There, the macro is just _ , i.e. printf(_("WHITE"));

Note that the compiler does do some serious logic checking, so the above is not nearly as inefficient as one might think. At least gcc-4.6.1 on x86-64, even with -O0, compiles the above C to exactly the same code as
Code:

#include <stdio.h>

int main(void)
{
    printf("BLACK");
    putchar('\n');
    return 0;
}



All times are GMT -5. The time now is 03:23 PM.