Michael
Michael

Reputation: 585

"Expected identifier or '(' before int" error while trying to use define and functions together

I was trying to use define with functions in C but there is an error for multiply function's first line. It works when I run it without the define.

#include <stdio.h>

#define multiply(n1, n2) (n1 * n2)

// multiply function returns multiplication of two integers
int multiply(int number1, int number2) { //Error in this line
    return number1 * number2;
}

int main() {

    // Printing multiply(n1, n2)
    printf("%d\n", (3 * 2) );

    system("pause");
} // End main

Upvotes: 0

Views: 1957

Answers (2)

SACHIN GOYAL
SACHIN GOYAL

Reputation: 965

Even before compiling will check the function syntax , pre-processing will happen and all the macros will be expanded .

As you have defined multiple macro like below :

#define multiply(n1, n2) (n1 * n2)

multiply will be replaced with (n1*n2) during pre-processing . Hence , call would look like . Before preprocessing

int multiply(int number1, int number2) { //Error in this line
    return number1 * number2;
}

After preprocessing :

int (int number1*int number2) { //Error in this line
    return number1 * number2;
}

which is not valid in C .

There is no problem having same name macro as that of function .If you will change your macro like below : your program will compile .

#include <stdio.h>

#define multiply my_mult //pre-processing will not break function 

// multiply function returns multiplication of two integers
int multiply(int number1, int number2) { //Error in this line
    return number1 * number2;
}

int main() {

    // Printing multiply(n1, n2)
    printf("%d\n", (3 * 2) );

    system("pause");
} // End main

In this example we have same name function as well as macro but still it compiles because here pre -processing is not breaking it .

Upvotes: 2

aliasm2k
aliasm2k

Reputation: 901

The error occurs as multiply is already defined as a macro. Then you are trying to redefine multpily as a function.

Try changing any one of their names. It should fix the error.

Upvotes: 0

Related Questions