Search code examples
c++macroslibxml2

error: expected primary-expression before ‘if’


here is my code, I don't know where is wrong near 'if', and what is "primary-expression" in c?

xml_parser.h

#define xpath(smth, exp) if (sizeof(*smth) == sizeof(xmlNode)) { xpath_node((xml_node_ptr)smth, exp); } else{ xpath_doc((xml_doc_ptr)smth, exp); }

xml_node_ptr *xpath_node(xml_node_ptr n, str exp);

xml_node_ptr *xpath_doc(xml_doc_ptr n, str exp);

xml_parser_test.cpp

TEST_F(XmlParserTest, xpath2) {
    xml_node_ptr n = xpath(d, "/html/body");
    xpath(n, "/div");
}

here is my output:

/home/roroco/Dropbox/rbs/ro_sites/c/xml_parser_test.cpp: In member function ‘virtual void XmlParserTest_xpath2_Test::TestBody()’:
/home/roroco/Dropbox/rbs/ro_sites/c/xml_parser.h:17:26: error: expected primary-expression before ‘if’
 #define xpath(smth, exp) if (sizeof(*smth) == sizeof(xmlNode)) { xpath_node((xml_node_ptr)smth, exp); } else{ xpath_doc((xml_doc_ptr)smth, exp); }
                          ^
/home/roroco/Dropbox/rbs/ro_sites/c/xml_parser_test.cpp:26:22: note: in expansion of macro ‘xpath’
     xml_node_ptr n = xpath(d, "/html/body");
                  ^

my full source is here


Solution

  • Your code is pretty much being expanded to

    xml_node_ptr n = if (sizeof(*d) == sizeof(xmlNode)) { xpath_node((xml_node_ptr)d, "/html/body"); } else{ xpath_doc((xml_doc_ptr)d, "/html/body"); }
    

    by the preprocessor. Pretty obvious that's wrong. To answer your second question, primary-expression is the expected non-terminal in the C++ grammar. The primary expression is something like arithmetic, function calls, etc.