开发者

Return with Macro C programming

This code is always returning -1 even when the fopen() function has executed successfully. Is there something I am ignoring.

void nullCheck(FILE* checkVar)  {
    if(checkVar==NULL)  {
        #define _NULL_ERROR
      }
    }

int readFile(char* _name, char* storeArray) {
FILE* fp;
fp=fopen(_name,READ_ONLY_MODE);
nullCheck(fp);
#ifndef _NULL_ER开发者_开发问答ROR
    char c=0;
    while((c=getc(fp))!=EOF) {
        *(storeArray+i)=c;
        i+=1;
    }
#endif
#ifdef _NULL_ERROR
    #undef _NULL_ERROR
    return -1;
#endif
return 1;
}

Thanks!


Oy va voy! Macros are defined and undefined when your code is compiled, not when it runs! They are not affected by control flow statements like "if" and "then" -- they are all processed before compilation of those statements even begins!


You need to re-read the documentation on the C Preprocessor. The #define _NULL_ERROR doesn't get executed when nullCheck is called, it gets interpeted when the preprocessor processes the file before it is compiled. So you are always setting _NULL_ERROR and so you will always return -1.


#define is a preprocessor command, which means it's not calculated / processed in the function nullCheck() but before the compiling of the code. so _NULL_ERROR is always defined and therefore the condition

#ifdef _NULL_ERROR
    #undef _NULL_ERROR
    return -1;
#endif

will always cause the pre-compiler to add the return -1; to your code.


This is what your code looks like to the compiler, after the preprocessor runs:

void nullCheck(FILE* checkVar)  {
    if(checkVar==NULL)  {
      }
    }

int readFile(char* _name, char* storeArray) {
FILE* fp;
fp=fopen(_name,READ_ONLY_MODE);
nullCheck(fp);
    return -1;
return 1;
}

As has been stated above, the preprocessor deals with macros before the compiler runs.


#define, #ifdef, and friends don't work like you think they do. They're preprocessor directives that affect your code even before the compiler sees it. Get your compiler to show you the preprocessed source before it compiles (-E or -save_temps in gcc and clang) and you'll immediately see what's going on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜