Reputation: 43
Say I have a member function that returns an integer, would it be considered bad practise on the odd occasion to call the member function and not store the return value.
Edit.
An example of this would be a function that appends an item to a vector and returns the index of the appended item.
A simplified example.
#include <vector>
using namespace std;
vector<int> myVector;
int AppendVector(int value)
{
myVector.push_back(value);
}
int main()
{
AppendVector(3);
AppendVector(4);
int indexOfValue = AppendVector(2);
// do action on appended value
}
Upvotes: 1
Views: 193
Reputation: 36832
No, and it is quite common to do so. There are plenty of functions which are used regularly while ignoring the return value.
Some examples you've likely used or seen:
std::printf
which returns the number of characters written.operator<<
which returns the stream, and is ultimately discardedstd::vector::erase
which returns an iterator just after the last element removedstd::map::insert
which returns an iterator and a statusFor cases where the return value is especially important, C++17 added the [[nodiscard]]
attribute.
Proior to C++17 you'd have to use something compiler specific such as gcc's __attribute__((warn_unused_result))
. See this answer for more detail.
Upvotes: 8
Reputation: 73101
It's going to depend entirely on what the return-value means, and what the caller is trying to accomplish by making the method-call.
The person writing the calling code should definitely be thinking about what (if anything) he wants to do with the return value, though; a common newbie mistake is to ignore a return value rather than examining it, and thus fail to act appropriately e.g. if the return value indicated that the method's operation has failed.
One semi-common idiom you might see is this:
(void) someObject.Method();
The (void) prefix doesn't do anything (the compiler will ignore it), but it does serve as an indicator to the human reader that the person who wrote that line is deliberately ignoring the return value, rather than failing to understand that a value was returned. It doesn't change the way the program behaves, but it does keep future readers of the source code from wondering if they are looking at a mistake or if the ignoring was intentional.
Upvotes: 2