How to Change the Value Defined in Define by Condition

Asked 1 years ago, Updated 1 years ago, 43 views

The header file defines #define SET_VALUE"%.3f" and
Assume that the source code contains several actions: str.Format(SET_VALUE,dValue);.

I'd like to perform a branching process that converts to 3 and 5 digits using the Format() method. One method is to define two #define definitions and

#define SET_VALUE3"%.3f" 
#define SET_VALUE5 "%.5f" 

Before the conversion process, for example,

 if (MODE==1)
{ 
     str.Format(SET_VALUE3,dValue)
}
else
{
    str.Format(SET_VALUE5,dValue)
}

I think there is a way to do this, but there are several places, so leave str.Format(SET_VALUE,dValue) as it is. #defineSET_VALUE values are divided into "%.3f", "%1.5f" and
SET_VALUE is defined as "%.3f" under certain conditions, and SET_VALUE is defined as "%.5f".
I would like to create a branch decision process, but is it possible to branch define?

I don't know if it has been conveyed, but please let me know.

c++

2022-09-30 21:42

2 Answers

int precision=MODE==1?3:5;
str.Format(".*f", precision, dValue);

and so on.Then, rather than defining a format string in a header file, shouldn't we define a function that returns a formatted string?


2022-09-30 21:42

If "specific conditions" are "determined at compile time", you can branch using #ifdef directives, etc.
Why don't you search by keywords such as "c language preprocessor directive"?

If "specific conditions" are "run-time-varying", then #define cannot do it, so
You may have to use it as a variable for the global string to be externally referenced.

For example, suppose str is CSstring.

externCSstring SET_VALUE;// (old) #defineSET_VALUE"%.3f"// format

You may have no choice but to create external variables as shown in to provide the entity and the function to set it up.

CSstring SET_VALUE;// (provisional) Global referenced externally
voidSetValue_Format_Change(ex_Mode)
{
    if(ex_Mode==1) {SET_VALUE="%.3f";} // SET_VALUE=SET_VALUE3
    else {SET_VALUE="%.5f";} // SET_VALUE=SET_VALUE5 equivalent features
}

However, this is only a proposal as a provisional measure.
This is because in this case, SET_VALUE's meaning has changed qualitatively from the previous one, so this declaration, definition, and reference should be changed according to the changed meaning.


2022-09-30 21:42

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.