[Solved] Recursive function:What is the difference between C++ and Python?


The C++ code doesn’t work perfectly. It’s undefined behavior and everything can happen. That includes working, just suddenly stopping to work tomorrow, or on Christmas eve and delete all your files…

C++ standard draft n4527 (6.6.3/2 [stmt.return]):

The expression or braced-init-list of a return statement is called its operand. A return statement with no operand shall be used only in a function whose return type is cv void, a constructor (12.1), or a destructor (12.4). A return statement with an operand of type void shall be used only in a function whose return type is cv void. A return statement with any other operand shall be used only in a function whose return type is not cv void; the return statement initializes the object or reference to be returned by copy-initialization (8.5) from the operand. [ Note: A return statement can involve the construction and copy or move of a temporary object (12.2). A copy or move operation associated with a return statement may be
elided or considered as an rvalue for the purpose of overload resolution in selecting a constructor (12.8). — end note ] [ Example:

std::pair<std::string,int> f(const char* p, int x) {
    return {p,x};
}

— end example ] Flowing off the end of a function is equivalent to a return with no value; this results in undefined behavior in a value-returning function.

It clearly specifies the undefined behavior at the end.

That it seems to work in your case is just a random accident, don’t count on it. Such code should be fixed.

So in the end it all boils down to python returning none if you don’t explicitly return something and C++ giving undefined behavior if you tell it that you want to return some type but don’t actually do.

0

solved Recursive function:What is the difference between C++ and Python?