I run my C code in vs2010 (win32 console application). It was compiled as C++ application.
#include "stdafx.h"
#define YES 1;
#define NO 0;
// function to determine if an integer is even
int isEven(int number)
{
int answer;
if ( number % 2 == 0)
answer = YES;
else
answer = NO;
return answer;
}
int main()
{
int isEven(int number);
if (isEven(17) == YES)
printf("yes ");
else
printf("no ");
if ( isEven(20) == YES)
printf("yes\n");
else
printf("no\n");
return 0;
}
Compiler error as below.
p300.cpp(18): error C2181: illegal else without matching if
p300.cpp(30): error C2143: syntax error : missing ')' before ';'
p300.cpp(30): error C2059: syntax error : ')'
p300.cpp(31): warning C4390: ';' : empty controlled statement found; is this the intent?
p300.cpp(33): error C2181: illegal else without matching if
p300.cpp(37): error C2143: syntax error : missing ')' before ';'
p300.cpp(37): error C2059: syntax error : ')'
p300.cpp(38): warning C4390: ';' : empty controlled statement found; is this the intent?
p300.cpp(40): error C2181: illegal else without matching if
Then I also tried to insert several of { } for each of if-else condition statement, but the code still compiled failed. What's wrong with my code?
The compile error is due to the semicolons on your #define statements. Remove them.
#define is a preprocessor macro, not c syntax. It doesn't need a semicolon. The preprocessor does straight substitution on YES and NO, which makes:
if ( number % 2 == 0)
answer = YES;
else
answer = NO;
Turn into:
if ( number % 2 == 0)
answer = 1;; // <-- Notice the two semicolons!
else
answer = 0;;
That makes two statements between if and else, so compiler errors ensue. I suspect you get different compiler errors when you add { and } due to
if (isEven(17) == YES)
becoming
if (isEven(17) == 1;)
By the way, this question is tagged c, but your filename is .cpp, which is a common suffix for c++. If you are using c++, definitely use the bool type.
bool is_even = true;
bool is_odd = false;
to start with, remove the semicolons from the end of the defines
#define YES 1
#define NO 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With