Do all C++ operators return something?

C++Operators

C++ Problem Overview


All C++ operators that I have worked with return something, for example the + operator returns the result of the addition.

Do all C++ operators return something, or are there some C++ operators that do not return anything?

C++ Solutions


Solution 1 - C++

No, not all operators return something.

Although they are probably not exactly what you are thinking about, note that the delete and delete[] C++ 'keywords' are actually operators; and they are defined as having the void return type - which means they evaluate to nothing (which is not 'something').

From cppreference:

> > void operator delete ( void* ptr ) noexcept; > void operator delete[]( void* ptr ) noexcept; >

Solution 2 - C++

Operators of custom types can be overloaded to do the most weirdest things.

> for example the + operator returns the result of the addition.

Not necessarily:

#include <iostream>
struct foo {
    int value = 0;
    void operator+(int x) {
        value += x;
    }
};

int main () {
    foo f;
    f + 3;
}

Here operator+ adds the left hand side to the value member, and its return type is void. This is a made-up example, but, in general, not returning something from a custom operator is not unusual.

The only operator that can be overloaded and that has the requirement of returning something, that I am aware of, is operator->. It must either return a raw pointer or an object that has an operator->.

Solution 3 - C++

To nitpick, operators don't return anything. They are just lexical elements that we use to create expressions in the language. Now, expressions have types and may evaluate to values, and I assume this is what you mean by operators "returning things".

And, well, yes. There are C++ expressions with type void (and consequentially don't evaluate to any value). Some are obvious, others less so. A nice example would be

throw std::runtime_error()

throw is an expression under the C++ grammar. You can use it in other expressions, for instance in the conditional expression

return goodStatus() ? getValue() : throw std::runtime_error();

And the type of a throw expression, is void. Obviously since this just causes execution to rapidly go elsewhere, the expression has no value.

Solution 4 - C++

None of the built-in C++ operators return something. Overloaded C++ operators return something insofar that the operator notation is a syntactic sugar for a function call.

Rather, operators all evaluate to something. That something has a well-defined value as well as a type. Even the function call operator void operator()(/*params*/) is a void type.

For example, +'a' is an int type with the value of 'a' encoded on your platform.

If your question is "Can C++ operators have a void return type?" then the answer is most certainly yes.

Solution 5 - C++

You can actually define a function call operator to return nothing. For example:

struct Task {
   void operator()() const;
};

Solution 6 - C++

operator void(): user defined conversion function to void

You may define the peculiar operator void() conversion function, where the compiler will even warn you that the T to void conversion function will never be used:

#include <iostream>

struct Foo {
    operator void() { std::cout << "Foo::operator void()!"; }
    // warning: conversion function converting 'Foo' to 
    //          'void' will never be used
};
    
int main() {
    Foo f;
    (void)f;            // nothing
    f.operator void();  // Foo::operator void()!
}

as governed by [class.conv.fct]/1

> [...] A conversion function is never used to convert a (possibly > cv-qualified) object to the (possibly cv-qualified) same object > type (or a reference to it), to a (possibly cv-qualified) base class > of that type (or a reference to it), or to (possibly cv-qualified) > void.117 > > (117) > These conversions are considered as standard conversions for the > purposes of overload resolution ([over.best.ics], [over.ics.ref]) and > therefore initialization ([dcl.init]) and explicit casts. A > conversion to void does not invoke any conversion function > ([expr.static.cast]). Even though never directly called to perform a > conversion, such conversion functions can be declared and can > potentially be reached through a call to a virtual conversion function > in a base class.

Whilst, however, as is shown above, you can still invoke it using the explicit .operator void() syntax.

Solution 7 - C++

The operators defined (builtin) by the language are tokens used to perform different kinds of computations:

  • arithmetic (+,-,*,/)
  • increment/decrement (++,--)
  • assignment (=,+=,-=,*=,/=,%=,>>=,<<=,&=,^=,|=)
  • logic (!,&&,||)
  • relational (==,!=,>,<,>=,<=)
  • conditional ?
  • comma

and so on. The list can be very extensive.

In language references like this one or this one, these are not necessarily referenced as returning something, just performing an arithmetic or logic operation, a comparison by which means a variable may be modified, etc.

Since this operation results in some value, it may be interpreted as been "returned" by the operator, but it is different from a function return value.

The overloaded operators, on the other hand, can be defined with a return value of some type, even that can be void, so, no, not all operators return some value in C++.

Solution 8 - C++

I'm assuming you're talking about operator functions and not operators as a syntactic unit of the language.

If you overload operators on any type, you may actually return whatever you want.

This also makes a lot of sense, because operations like * or () may sometimes very intuitively not return their input type. Imagine multiplying a complex number type with a real number type. Or an operator that returns an element from a collection.

You may also overload the ++ and -- operators to not return anything thus removing the extremely error-prone mixing of side-effect and expression value that the standard version has.

Solution 9 - C++

No. Consider these two examples here:

int multiply (int a, int b) {
   return a*b;
}

void multiply_void(int a, int b) {
   cout << a*b;
//or cout << multiply(a,b);
}

First function will return an integer value which can be used by another function. The value is returned and stored in memory to be used when necessary. If not, it is not visible to human & just sits happily in the memory.

Second function will output to the default output device(usually console). The value returned by the multiplication operator is passed to an output device. The function multiply_void does not return an actual value.

Solution 10 - C++

All operators return something. They are called operators because they operate something , therefore they will return something. Those Operators who do not return something cant be called operators. Either they will return some value or return True or False depending upon the situation.

Solution 11 - C++

Operators on their own do not necessarily return anything. Function calls return values. Operators can result in values. Operators can sometimes invoke functions. Examples include:

• The function call operator.

• An overloaded operator that gets transformed into a function call.

• operator new, which is invoked as part of a new-expression, is a function call.

My only purpose in mentioning function calls is to clarify the result vs. return. Based on looking at all 126 instances of “return” and words derived from it in [expr], the section seems to carefully use the word return to refer to:

• the result of a function call

• aspects of control flow related to coroutines

OK, that’s enough pedantry on result vs. return.

Solution 12 - C++

C++ Operators return something or not is depends upon how you used them. Built-In C++ operators return some value until and unless enforced to return void.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser8240761View Question on Stackoverflow
Solution 1 - C++Adrian MoleView Answer on Stackoverflow
Solution 2 - C++463035818_is_not_a_numberView Answer on Stackoverflow
Solution 3 - C++StoryTeller - Unslander MonicaView Answer on Stackoverflow
Solution 4 - C++BathshebaView Answer on Stackoverflow
Solution 5 - C++ネロクView Answer on Stackoverflow
Solution 6 - C++dfribView Answer on Stackoverflow
Solution 7 - C++ram0nvaldezView Answer on Stackoverflow
Solution 8 - C++KafeinView Answer on Stackoverflow
Solution 9 - C++Gokhan DilekView Answer on Stackoverflow
Solution 10 - C++Alby View Answer on Stackoverflow
Solution 11 - C++SaddamView Answer on Stackoverflow
Solution 12 - C++user13986534View Answer on Stackoverflow