user8240761
user8240761

Reputation: 995

Do all C++ operators take operands?

All C++ operators that I have worked with takes operands, for example the + operator takes two operands.

Do all C++ operators take operands, or are there some C++ operators that do not take any operand?

Upvotes: 2

Views: 275

Answers (1)

Bathsheba
Bathsheba

Reputation: 234785

throw in its nullary form is the only operator that doesn't take an argument. Consider:

#include <cstdlib>
#include <ctime>
#include <iostream>

void foo()
{
    try {
        std::srand(std::time(0));
        throw rand() % 2;
    } catch (int n){
        std::cout << "foo " << (n ? n : throw);
    }
}

int main()
{
    try {
        foo();
    } catch (int n){
        std::cout << "main " << n;
    }
}

where throw (which in its nullary form throws the current exception by reference) is clearly an operator since it can be written within the ternary conditional operator. foo will throw an exception approximately 50% of the time, with the output in either case yielding a primitive sort of stack trace.

noexcept without an operand is not an operator but a specifier, so that doesn't count.

Upvotes: 4

Related Questions