Search code examples
cc-preprocessorpreprocessor-directive

Error returning 1 when comparing strings


Can anyone tell me why Visual Studio is giving me an error when I try to return 1 by using my define ERROR macro? VS says its expecting a bracket :/

#define ERROR "A generic error has occured";

const char *RetAdapters(int *adapters) {

    if(...) {} 

    else
        return ERROR;
} 


int main()
{
    const char *ret = RetAdapters(&input);

    if (strcmp(*ret, ERROR) == 0) {
        return 1;
    }

    return 0;

}

Solution

  • The definition of ERROR contains a trailing ; which causes a syntax error when ERROR gets expanded in if (strcmp(*ret, ERROR) == 0) {

    Remove the ; from the macro definition and also remove the indirection *:

    #define ERROR "A generic error has occurred"
    
    const char *RetAdapters(int *adapters) {
        if (...) {
            ... 
        } else {
            return ERROR;
        }
    } 
    
    int main() {
        const char *ret = RetAdapters(&input);
    
        if (strcmp(ret, ERROR) == 0) {
            return 1;
        }
        return 0;
    }
    

    Note however that this programming style is not recommended:

    • ERROR could be defined as a global variable:

      const char ERROR[] = "A generic error has occurred";
      
    • RetAdapters() could return a error status, different from 0 and return 0 for success. This is how most system calls report success and failure on unix systems, and this is how main() is supposed to report successful operation to the system.