Eduardo Eduardo -4 years ago 106
C Question

How do I use if statement in C?

I'm trying to make a program that calculates the sum of two integers, and i don't know how to use If. My intent was to print a message if one (or both) number is negative.

An error appears if i try to compile this, it says me: 'else without a previous if'

Here is the code.

#include <stdio.h>
int num1, num2, numf;
printf("type a number ");
scanf("%d", &num1);
if (num1<0);
printf("you must type only positive numbers");
printf("type a number ");
scanf("%d", &num2);
if (num2<0);
printf("you must type only positive numbers");
printf("%d + %d = %d", num1, num2, numf);

Answer Source

The problem that you have is the extra ; at end of if statement. It terminates the if statement block. The following print statement is not considered as the associated statement anymore, it becomes an unconditional statement. Thus, the following else becomes detached to the previous if statement which is erroneous syntax.

To use the standard terminologies, quoting directly from the C11, chapter ยง6.8.4,


if ( expression ) statement else statement


An else is associated with the lexically nearest preceding if that is allowed by the syntax.

If you want a corresponding else clause, you need to get that associated with previous if statement, i.e., it should follow the if condition statement block. In your case, removing the trailing ; from the expression condition will do the job. Something like

if (num1<0)              //removed ;
{                       //associated block start
    printf("you must type only positive numbers");
}                       //associated block end
else                    // no else is associated with lexically nearest preceding if
    printf("type a number ");

That said,

  • For a hosted environment, the conforming signature of main() is int main(void).
  • Always check for the return value of scanf() to ensure success before using the scanned value.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download