How to avoid conflict between the definition of a function and macro with the same name?

113 Views Asked by At

I've defined a function and a macro like this to set the values inside of a matrix:

void init_matrix(Matrix *mat, double ea[],  size_t size)
{
    for (int i = 0; i < mat->row; i++)
        for (int j = 0; j < mat->col; j++) {
            if (!(i*mat->col+j<size))
                return;
            mat->entries[i][j] = ea[i*mat->col + j];    
        }
}

#define init_matrix(mat, ...) init_matrix(mat, (double []) {__VA_ARGS__}, sizeof((double []) {__VA_ARGS__})/sizeof(double))

It works fine now, but I was considering moving the function declarations and macros into a header file and then including that header file into this program. But when I do that, it'll probably make expand the definition of the function into something like:

void init_matrix(Matrix *mat, (double []) {double ea[], size_t size}, sizeof((double []) {double ea[], size_t size})/sizeof(double))

Which would mess everything up, right? How can I avoid that? Maybe putting this function at the end of the file and using an #undef init_matrix before it? Or is there a way to undefine a macro just in a section of the code and keep it working like it did before before and after that part?

2

There are 2 best solutions below

0
David Ranieri On BEST ANSWER

You can use parentheses around the function name (and around the name in the prototype if you are using a header) to stop the expansion:

void (init_matrix)(Matrix *, double[], size_t);
void (init_matrix)(Matrix *mat, double ea[], size_t size)
{
    ...
}

Take a look to What do the parentheses around a function name mean? for more info.

1
KamilCuk On

How to avoid conflict between the definition of a function and macro with the same name?

Name the macro differently from the function.

Do not confuse users. Follow the typical convention of macro names being in upper case letters. Let it be clear what is a macro and what is not. Let users be clear about what kind of initialization they are requesting.

void init_matrix(Matrix *mat, double ea[],  size_t size)
{
    for (int i = 0; i < mat->row; i++)
        for (int j = 0; j < mat->col; j++) {
            if (!(i*mat->col+j<size))
                return;
            mat->entries[i][j] = ea[i*mat->col + j];    
        }
}

#define INIT_MATRIX(mat, ...)  init_matrix(mat, (double []) {__VA_ARGS__}, sizeof((double []) {__VA_ARGS__})/sizeof(double))