Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Do you think that this is a case of dangling else?

According to compiler and IIT professor it is. But I have doubt! According to theory, after condition of if is met, it will always process further only ONE statement (or one compound statement i.e. multiple statements enclosed within bracket). Here, after first if is processed and met, the compiler should consider immediate statement that is another if and check for the condition. If condition is not met, then compiler will not display any result as we don't have any associated else with printf function saying condition is not met (i.e. n is not zero).

Here, compiler should always associated given else in program with first if clause because all the statement given after first if is not enclosed in brackets. So, why there is a scenario of dangling else here?

#include <stdio.h>

void main(void)
{
  int n = 0;
  printf("Enter value of N: ");
  scanf("%d",&n);
  if (n > 0)
  if (n == 0)
    printf("n is zero
");
  else
    printf("n is negative
");
  getch();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
170 views
Welcome To Ask or Share your Answers For Others

1 Answer

Per Wikipedia's definition of dangling else, you do have a dangling else statement.

C makes your code unambiguous. Your code is interpreted as:

if (n > 0)
{
   if (n == 0)
   {
      printf("n is zero
");
   }
   else
   {
      printf("n is negative
");
   }
}

Had you meant the code to be interpreted as:

if (n > 0)
{
   if (n == 0)
   {
      printf("n is zero
");
   }
}
else
{
   printf("n is negative
");
}

you would be surprised.

FWIW, no matter which interpretation is used, your code is wrong.

What you need to have is:

if (n > 0)
{
   printf("n is positive
");
}
else
{
   if (n == 0)
   {
      printf("n is zero
");
   }
   else
   {
      printf("n is negative
");
   }
}

or

if (n > 0)
{
   printf("n is positive
");
}
else if (n == 0)
{
   printf("n is zero
");
}
else
{
   printf("n is negative
");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...