Resend a string from the #define function

advertisements

I know you can return a character string from a normal function in C as in this code

#include <stdio.h>

char* returnstring(char *pointer) {
    pointer="dog";
    return pointer;
}

int main(void)
{
    char *dog = NULL;
    printf("%s\n", returnstring(dog));
}

However, I can't find a way to be able to return character strings in #define functions, as in this code

#include <stdio.h>

#define returnstring(pointer) { \
   pointer="dog"; \
   return pointer; \
}

int main(void)
{
    char *dog = NULL;
    printf("%s\n", returnstring(dog));
}

I know that there are workarounds(like using the first program). I just want to know if it is possible


Thinking about a "#define function" is, IMO, the wrong way to approach this.

#define is a blunt instrument which amounts to a text find/replace. It knows little to nothing about C++ as a language, and the replace is done before any of your real code is even looked at.

What you have written isn't a function in its own right, it is a piece of text that looks like one, and it put in where you have written the alias.

If you want to #define what you just did, that's fine (I didn't check your example specifically, but in general, using #define for a function call and substituting the arguments is possible), but think twice before doing so unless you have an amazing reason. And then think again until you decide not to do it.