mercredi 22 juin 2016

?: unexpected behaviour - although condition is true, the ? part is not executed

Consider this code:

// Example program
#include <stdio.h>

typedef enum{
  enum_1,
  enum_2
}my_enum;
/* 
 * this is not how the function works but when I debug 
 * it will always returns enum_1 (verified when using the debugger)
 * so I hope this is enough
 */    
int fun_1(int arg_1){return enum_1;} 
const int const_1 = 10;
const int const_2 = 20;
int main()
{
    int arg_1 = 0;

    int var_1 = fun_1(arg_1);

    int var_2 = (var_1 == (enum_1 
                    || enum_2))
                    ? const_1*10     // I expect this result
                    : const_2*10;    // instead I get this. why?
    printf("%d\n" , var_2);

    if(var_1==enum_1)
        var_2 = const_1*10;          // here it works fine        
    printf("%d\n" , var_2);

    return 0;
}

I'm debugging this code, and var_1 is expected to get the value of enum_1. It does, but somehow the "? :" operator does not give me the expected result - it does not assign const_1*10 to var_2 but const_2*10. When I move along in the debug and go to the if statement I get the expected result. Why is that?

I'm using windriver workbench on windows 8.1

EDIT

I changed the example to a runnable version, and as mentioned by tkausl, the problem was using (var_1 == (enum_1 || enum_2)) instead of (var_1 == enum_1 || var_1 == enum_2))

Aucun commentaire:

Enregistrer un commentaire