-1

I'm trying to create a XOR operator and for an unknown reason my compiler doesn't accept bool xor() as a function, neither does it allow me to call it or use it in any way possible.

I'd like to note that I'm following a book to learn C++. Specifically it's "Learn C++ From the Ground Up" by Herbert Schildt (3rd Edition) This piece of code is referenced in this book.

My code here works just fine if i name the function bool xar() or bool XOR(), but since I'm trying to learn C++ I'd like to gain some insight on why this error occurs.

#include <iostream>
using namespace std;

bool xor(bool a, bool b);

int main()
{
    bool q, p;
    cout << "Enter Q (0 or 1): ";
    cin >> q;
    cout << "Enter P (0 or 1): ";
    cin >> p;

    cout << "Q AND P: " << (q && p) << '\n';
    cout << "Q OR P: " << (q || p) << '\n';
    cout << "Q XOR P: " << xor(q, p) << "\n";
    cout << "nice";

    return 0;
}


bool xor(bool a, bool b)
{
    return (a || b) && !(a && b);
} ```

// The error message i receive is from the lines:
// ---------------------------
// bool xor(bool a, bool b);
// *expected an identifier*
// ---------------------------
// cout << "Q XOR P: " << xor(q, p) << "\n";
// *expected an expression*
// ---------------------------
// bool xor(bool a, bool b)
// *expected an identifier*
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93

1 Answers1

10

xor is a keyword and cannot be used as a name in your code. C++ offers Alternative operator representations so that instead of doing || for or you can use or. There is an xor for ^ so you cannot use that name.

Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • Thank you for the quick response. The book i'm using is quite old and a lot of thing must have changed since the day the 3rd edition was published. – Tass Tsourtzouklis Jul 24 '19 at 20:50
  • 1
    @TassTsourtzouklis yeah, you might try to select a book from curated list here: https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – SergeyA Jul 24 '19 at 20:51
  • 1
    @TassTsourtzouklis AFAIK these alternatives have always existed, just a lot of books don't cover them. Most coders use the symbols instead of the names so most books don't even touch on them because the symbols are what you'll see the vast majority of the time. – NathanOliver Jul 24 '19 at 20:52
  • @TassTsourtzouklis some compilers like VisualStudio's compiler don't have those keywords as keywords. This may be the reason why the thing slipped in – Aykhan Hagverdili Jul 24 '19 at 20:52
  • 1
    @Ayxan There is an option to make them keywords. fun read on the subject: https://stackoverflow.com/questions/24414124/why-does-vs-not-define-the-alternative-tokens-for-logical-operators – NathanOliver Jul 24 '19 at 20:56
  • @NathanOliver Not always (in pre-standard dialects of C++). The book appears to have been written pre-standardisation. – eerorika Jul 24 '19 at 22:23