This post is older than 2 years and might not be relevant anymore
More Info: Consider searching for newer posts

If-else chain not working properly.

Hi,

I am using nRF52840 DK, and I am creating my program starting from the basic UART example. I am not using threads, just plain sequential execution. I have a chain of if-else statements, like this:

if (condition1){
    //do something;
}else if (condition2){
    //do something else;
}else if (condition3){
    //do this;
}else if (condition4){
    //do that;
}else if (condition5){
    printf;
    call to function x;
}else{
    printf("no condition found");
}

The inputs fulfill condition5, but the code doesn't go into condition5. I have copied just above the code a simple if(condition5), and printf something, and it does go into that if statement, so condition5 is indeed fulfilled. I have also tried debugging step by step, and the execution jumps from the evaluation of if(condition4) to the last else directly, it doesn't even go into evaluating condition 5. If I change the order of the conditions and put condition5 first, it does work, but I need to add around 10 more conditions and the code would get quite messy if I don't put the conditions in any logical order.

I also know that it's better to use a switch, but in C I cannot do a switch of a string, so I am using an array and making conditions like if((command[0]==108)&(command[1]==101)&(command[2]==100)&(command_length==3))//led 

Any idea on how to handle this problem would be greatly appreciated. Thank you very much.

Parents Reply Children
Related