I am using visual studio c++. I want to be able to switch between double and long long. How can I use #ifdef in the following program? I want to use a more simpler solution to handle the case of multiple printf.
//#define TYPE_SWITCH
#ifdef TYPE_SWITCH
typedef double myType;
#else
typedef long long myType;
#end
.
.
.
int main()
{
myType a;
#ifdef TYPE_SWITCH
printf ("my value is %lf",a); // I have many printf or scanf and I want to use a simple macro here
#else
printf ("your value is %l",a/10); // I have many printf or scanf and I want to use a simple macro here
#endif
}
You could use something like that:
//#define TYPE_SWITCH
#ifdef TYPE_SWITCH
typedef double myType;
#def PATTERN_MY_TYPE "%lf"
#def MODIFICATOR(a) (a)
#else
typedef long long myType;
#def PATTERN_MY_TYPE "%l"
#def MODIFICATOR(a) (a/10)
#end
#def PATTERN_INT "%d"
//...
int main() {
myType a;
printf(PATTERN_MY_TYPE ", " PATTERN_INT, MODIFICATOR(a), 42);
}
The compeiler can concate strings while compeiling so you can use "foo" "bar"
to create the string "foobar"
the same works for defines. ( "foo" PATTERN_INT "bar"
would produce "foo%dbar"
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.