C Preprocessor and if-else statement

I am running my C code in vs2010 (win32 console application). It was compiled as a 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 shown 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 a few of { }for each of the condition statements if-else, but the compiled code did not work. What happened to my code?

+3
source share
4 answers

A compilation error is related to the semicolon in your statements #define. Remove them.

#define - , c. . YES NO, :

if ( number % 2 == 0)
    answer = YES;
else
    answer = NO;

:

if ( number % 2 == 0)
    answer = 1;;  // <-- Notice the two semicolons!
else
    answer = 0;;

if else, . , { } -

if (isEven(17) == YES)

if (isEven(17) == 1;)

, c, .cpp, ++. ++, bool.

bool is_even = true;
bool is_odd = false;
+6

,

#define     YES     1
#define     NO      0
+2

, . , , .

, C.

1) .

i.e 'NO' uint16_t uint32_t.

int. , 16- , 16 . NO. , NO . , "", , . , , 32- .

  • Casting , .

:

#define     YES     1  
#define     NO      0

:

#define     YES  (uint16_t)   1  
#define     NO   (uint16_t)   !(YES)  

, : 0xFFFF. , , . , , , , , :

#define MY_LARGE_CONSTANT    0xFFFFU

"U". , .

, , . . , , , .

+2

nothing to do by putting a semicolon in a statement #define. It just becomes part of the macro. You identified

#define     YES     1;

So, your main function will look like this:

int main()
{
    int isEven(int number);

    if (isEven(17) == 1;)
        printf("yes "); 
    else
        printf("no ");


    if ( isEven(20) == 1;)
        printf("yes\n");
    else
        printf("no\n");

     return 0;
}

While there is nothing wrong with placing a semicolon, in this case you probably want to remove the semicolon, and then the statement will become what you want.

+1
source

Source: https://habr.com/ru/post/1751128/


All Articles