Question

I am trying to make use of #define's in a program code, similar to this (simplyfied to the bone) example code:

#define M 20
#define N 10

void foo(int *a) {
    if (a == M) { printf("Hello!\n"); }
    else if (a == N) { printf("Goodbye!\n"); }
return;
}
int main(void) {
    foo(M);
    return(0);
}

When trying to compile this, I get the following error output:

main.cpp||In function ‘void foo(int*)’:|
main.cpp|6|error: ISO C++ forbids comparison between pointer and integer [-fpermissive]|
main.cpp|10|note: in expansion of macro ‘M’|
main.cpp|7|error: ISO C++ forbids comparison between pointer and integer [-fpermissive]|
main.cpp|11|note: in expansion of macro ‘N’|
main.cpp||In function ‘int main()’:|
main.cpp|15|error: invalid conversion from ‘int’ to ‘int*’ [-fpermissive]|
main.cpp|9|error:   initializing argument 1 of ‘void foo(int*)’ [-fpermissive]|
||=== Build finished: 4 errors, 0 warnings (0 minutes, 0 seconds) ===|

Now, obviously something is wrong here. The purpose of this code is to specify an integer value that can be passed over to the prototype, without having to remember the value of the integer when writing the code. The technique seems to be commonly used in association with sockets, where AF_INET and AF_INET6 represents two different integer values. In that way you don't have to remember the value for the IPv6-protocol if that's the one you would like to us for a socket, you only have to specify AF_INET6.

Q: How should I write this code to make it work?

Was it helpful?

Solution

Foo is accepting a pointer to an Int. not an int value. Your define turns into an integer literal. And will work anywhere an integer literal will work.

You cannot get the address of a literal.

try :

void foo (int a) {

or actually creating a integer variable, and passing the address of it to foo, and dereferencing it in foo back to an int :

int main (void)
{

    int myVar = M;
    foo(&myvar)
}

void foo (int *a) {

    if (*a == M) { printf("Hello!\n"); }
    else if (*a == N) { printf("Goodbye!\n"); }
    return;
}

OTHER TIPS

You do understand that the pre-processor is a very simple creature.

It just replaces any M with 20. I.e. Not a pointer.

So change

 void foo(int *a) {

to

 void foo(int a) {

The error message says it all. You are comparing a pointer to an integer value whereas what you intent to do is to compare value stored at the location pointed by pointer a to M or N.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top