Use of condicinals in macros

-2

Good evening! I want to test a condition that will be implemented in the macro. The value for the test will be informed by the user. My code generates an error when compiling. What can it be? Thanks!

#include <stdio.h>.
#define Epar(x)((x)%2)?1:0

int main()
{
    int x;
    printf("Informe um numero: \n\n");
    scanf("%d", x);
    Epar(x);
}
    
asked by anonymous 21.05.2018 / 02:52

2 answers

0

You use macro to check if the value of x is even. In addition, it makes use of the ternary operator, which is an alternative to override the if-else . Well, remembering the syntax of this operator, we have the following definition:

  

condition? true: false

From this syntax, it is noted that there is no well-defined condition in the condition for the ternary operator, only an (x% 2) operation. If the goal is to verify that the value x is even, the correct one is to use ((x% 2) == 0) , so that there is verification of the result of the operation and it will be possible to return 1 for true cases and 0 for false cases.

Two errors are apparent in your code.

i. The character. (dot) is in an unsuitable location in the stdio.h library definition - which will cause the compiler to point to an extra tokens error.

#include <stdio.h>.

ii. In the step of assigning value to the variable x, the & is absent - which makes it impossible to read the entered data.

scanf("%d", x);

An interesting point to note is that because macros are strings substitutions, it is good programming practice to use parentheses around their elements - especially to ensure that operator precedence is handled correctly.

Given the above, your code will compile without errors in this way:

#include <stdio.h>
#define Epar(x) ((((x) % 2) == 0) ? 1 : 0)

int main()
{
    int x;
    printf("Informe um numero: \n\n");
    scanf("%d", &x);

    if(Epar(x))
    {
        printf("\nNumero par");
    }
    else
    {
        printf("\nNumero impar");
    }

    return(0);
}
    
21.05.2018 / 13:22
0

That point after #include <stdio.h> will certainly cause the compiler to return an error like this:

teste.c:1:19: warning: extra tokens at end of #include directive [enabled by default]
 #include <stdio.h>.
                   ^

Here is a corrected and tested code that can solve your problem:

#include <stdio.h>

#define EhPar(x)    (!(x % 2))

int main()
{
    int n;

    printf("Informe um numero: ");
    scanf( "%d", &n );

    if( EhPar( n ) )
    {
        printf("%d eh um numero par!\n", n );
    }
    else
    {
        printf("%d eh um numero impar!\n", n );
    }

    return 0;
}
    
21.05.2018 / 05:47