Adam Naylor
Adam Naylor

Reputation: 6330

Can someone explain the c++ FAILED function?

I've seen a lot of example c++ code that wraps function calls in a FAILED() function/method/macro. Could someone explain to me how this works? And if possible does anyone know a c# equivalent?

Upvotes: 4

Views: 8305

Answers (3)

OregonGhost
OregonGhost

Reputation: 23759

And if possible does anyone know a c# equivalent?

You won't actually need that in C#, unless you're using COM objects. Most .NET functions either already return a (more or less) meaningful value (i.e. null, false) or throw an exception when they fail.

If you're directly accessing a COM object, you can define a simple Failed function that does what the macro in unwind's post does. Define that locally (protected/private), since the messy COM details shouldn't be visible in your app anyway.

In case you didn't know, there's also a SUCCEEDED macro in COM. No need to test for failure :)

Upvotes: 0

Johann Gerell
Johann Gerell

Reputation: 25581

It generally checks COM function errors. But checking any function that returns a HRESULT is what it's meant for, specifically. FAILED returns a true value if the HRESULT value is negative, which means that the function failed ("error" or "warning" severity). Both S_OK and S_FALSE are >= 0 and so they are not used to convey an error. With "negative" I mean that the high bit is set for HRESULT error codes, i.e., their hexadecimal representation, which can be found in, e.g., winerror.h, begins with an 8, as in 0x8000FFFF.

Upvotes: 8

unwind
unwind

Reputation: 399833

This page shows the half of the WinError.h include file that defines FAILED(). It's actually just a very simple macro, the entire definition goes like this:

#define FAILED(Status) ((HRESULT)(Status)<0)

Upvotes: 2

Related Questions