0

In C++, how to handle function outputs , if the inputs are invalid. Say, I am writing a function to multiply two matrices. How to deal with it if the two matrices cannot be multiplied (due to in-compatible shape)?

I tried to use std::optional , but then it has created other problems. Since the output is expected to be std::optional(Matrix) ,I have to write all the other functions in the class (like print Matrix()) with the expected output as std::optional , which seems unnecessary.

3
  • If you have a std::optional(Matrix) and want to pass it to a function that accepts a Matrix then you have to skip calling the function if the std::optional contains no Matrix. Commented Jan 27, 2024 at 11:05
  • 1
    If writing a function to multiply two matrices, the information about dimensions of those matrices must be passed somehow, otherwise the function can not do the required actions. So check the dimension for validity. There are various options for handling cases where the dimension are invalid (e.g. return an error code, pass a variable via a pointer or reference argument and modify that, throw an exception, ....). The choice depends on needs of your application. std::optional strikes me as unnecessary, but if that's what you're required to do .... Commented Jan 27, 2024 at 11:10
  • 1
    exceptions are zero cost if they don't get thrown, don't be hesitant to throw an exception so long as you explicitly document in Bold that your functions can throw, plus this simplifies overloading operators for your classes, alternatively if you are willing to write all your code in a functional style then you can use std::optional::and_then to chain operations, but you will need to check that the optional is not empty at some point. Commented Jan 27, 2024 at 11:28

2 Answers 2

0

I think this could be fun. Just add a 'valid' property to the Matrix and check it only when you want to!

class Matrix
{
public:
    Matrix Multiply(Matrix other)
    {
       return Multiply(other, m_isValid);
    }

    bool IsValid()
    {
        return m_isValid;
    }

private:
    bool m_isValid;
    Matrix Multiply(Matrix other, bool& isValid);
};
Sign up to request clarification or add additional context in comments.

Comments

-1

Before attempting to multiply two matrices, ensure that the number of columns in the first matrix matches the number of rows in the second. If this condition is not met, throw an exception.

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.