简体   繁体   中英

warning C4127: conditional expression is constant

#define VALUE_MAX 300
int main() {
   if(VALUE_MAX)
      printf("The value is %d",VALUE_MAX);
   return 0;
}

When I try to compile the above program if(VALUE_MAX) is showing a warning

conditional expression is constant.

How to solve the above warning?

since the if condition becomes always true that is a constant ...

int main()
 {
// if(VALUE_MAX)
#ifdef VALUE_MAX
 printf("The value is %d",VALUE_MAX);
#endif
 return 0;
 }

In your code, VALUE_MAX is not a variable, it's a MACRO. MACROs can be considered as a textual replacement at preprocessing time. So,

  if(VALUE_MAX)

which is translated to

 if (300)

is always TRUE. It is equivalent to

  if(1)

which is having essentially no effect. The code block under the if condition will execute unconditionally.


EDIT: ( Elaboration for better understamding )

An if statement is called a selection statement . The syntax of simple if statement is

 if ( expression ) statement

based on the evaluation of expression , it is decided whether the following statement (or block) will be executed.

In case of your code,

  if(VALUE_MAX)

always evaluates to TRUE. In this scenario, the use of if statement is meaningless. YOu can get rid of the if statement altogether.

VALUE_MAX is replace with a number therefore the condition is replaced with

if(300)

which is always true.

ways to get around the warning:

  1. change VALUE_MAX to a variable

int VALUE_MAX = 300;

  1. change the condition to ifdef

#ifdef VALUE_MAX printf("The value is %d",VALUE_MAX); #endif

You probably want a (pre-)compile time macro "if" ( #ifdef ), rather than a runtime "if" ( if (…) ):

#define VALUE_MAX 300

int main() {
#ifdef VALUE_MAX
   printf("The value is %d", VALUE_MAX);
#endif
   return 0;
}

The code between #ifdef and #endif will be compiled if you have #define d the VALUE_MAX macro.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM