check123
check123

Reputation: 2009

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_ERROR
    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!

Upvotes: 0

Views: 304

Answers (5)

Carl Norum
Carl Norum

Reputation: 224864

#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.

Upvotes: 1

Jonathan
Jonathan

Reputation: 13624

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.

Upvotes: 1

jcopenha
jcopenha

Reputation: 3975

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.

Upvotes: 3

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

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!

Upvotes: 5

MByD
MByD

Reputation: 137312

#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.

Upvotes: 2

Related Questions