# Define, identify with # defines, if a parameter is default

Jul 6, 2009 at 11:39am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>
#include <string.h>

#define _minhaFuncao( a, b) MinhaFuncao(__FILE__, __LINE__, a, b);

void MinhaFuncao(char* sArqCPP, unsigned long ulLinhaCPP, char* msg, char *filename = NULL)
{
    FILE* pFile;
    if(filename == NULL)
        pFile = fopen("teste.txt", "w+t");
    else
        pFile = fopen(filename, "w+t");

    if(pFile == NULL )
    {
        printf( "Não foi possivel abrir o arquivo\n" );
        return;
    }

    char cAux[256];
    sprintf( cAux, "[%s - %lu] ", strrchr( sArqCPP, '\\')+1, ulLinhaCPP);  
    fwrite(cAux, sizeof(char), strlen(cAux),pFile);

    fwrite(msg, sizeof(char), strlen(msg), pFile);

    fclose(pFile);
}

int main(int argc, char* argv[])
{
    //Assim funciona
    _minhaFuncao("Ola Enfermeira!!!", "log.txt");

    //Assim não funciona
    //Não queria ser obrigado a passar NULL para o segundo parametro
    //mas não sei como fazer isso por DEFINE

    _minhaFuncao("Ola Enfermeira!!!", NULL);

    return 0;
}



My question is the following, as defined by # define, if a parameter is default? (in the case above)

char *filename = NULL

Thanks!
Jul 6, 2009 at 12:14pm
Default argument values and #defines have nothing to do with each other.

Your last parameter ('filename') is given a default value of NULL -- whatever that is #defined as.

Hence, you can call the function without supplying a filename:
1
2
_minhaFuncao("Hello Nurse!", "log.txt");
_minhaFuncae("Hello Nurse!");

Hope this helps.
Jul 6, 2009 at 12:40pm
Does not work...

TesteForum.cpp(43) : warning C4003: not enough actual parameters for macro '_minhaFuncao'
TesteForum.cpp(43) : error C2059: syntax error : ')'
Jul 6, 2009 at 12:52pm
Oops! I see your question. (Sorry, I just woke up.)

You are looking to play with Variadic Macros, which are defined by the C99 standard only -- but which are usable in most C++ compilers too...

Try #defining the macro as:
#define _minhaFuncao( ... ) MinhaFuncao(__FILE__, __LINE__, __VA_ARGS__ )

Sorry about not understanding your question earlier.

[edit] Oh, yeah, notice also how the macro definition does not end with a semicolon.

http://en.wikipedia.org/wiki/Variadic_macro
Last edited on Jul 6, 2009 at 12:53pm
Jul 6, 2009 at 1:04pm
Cool... Thanks!
Topic archived. No new replies allowed.