Use of cinnamon in macros

Asked

Viewed 45 times

-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? Thank you!

#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);
}
  • 4

    It is symptomatic that you have not put the error. The error has nothing to do with the macro. In fact I find it quite unnecessary to use this macro.

2 answers

0

That point after the #include <stdio.h> will surely 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>.
                   ^

Follows a corrected and tested code capable of solving 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;
}

0


You make use of macro to check if the value of x is even. Also, it makes use of ternary operator, which is an alternative to replace the if-lse. Well, remembering the syntax of this operator, we have the following definition:

condition ? true : false

Starting from this syntax, note that there is no well-defined condition for the ternary operator, only one operation (x % 2). If the goal is to verify that the x value is even, the correct is to use ((x % 2) == 0), because 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 . (dot) character is in an inappropriate location in the stdio library definition. h - which will cause the compiler to point to an error of extra tokens.

#include <stdio.h>.

ii. In the value assignment step for variable x, the operator & is missing - which makes it impossible to read the entered data.

scanf("%d", x);

There is also an interesting point: how macros are substitutions of strings, it is good programming practice to use parentheses around your elements - mainly to ensure that operator preceedences are handled correctly.

In view of 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);
}
  • Thanks! I really freaked out adding that point in the directive (I believe I was wrong when typing).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.