cdangling-else

What is exactly dangling-else problem in c?


How can the code work like this? Which if-else statements are linked with each other? So why is the output like that "$$$$$"?

#include <stdio.h>
int main() {
    int x = 11;
    int y = 9;

    if(x<10)
    if(y>10)
    puts("*****");
    else
    puts("#####");
    puts("$$$$$");
    return 0;
}

Solution

  • Save time. Use an auto formatter.

    Hopefully then "why is the output like that "$$$$$"?" is self apparent.

    #include <stdio.h>
    int main() {
      int x = 11;
      int y = 9;
    
      if (x < 10)
        if (y > 10)
          puts("*****");
        else
          puts("#####");
      puts("$$$$$");
      return 0;
    }