Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

c - Why is there a 'dangling else' scenario here?

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

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

1 Reply

0 votes
by (71.8m points)

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
");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...