0

Possible Duplicate:
What is the purpose of the statement “(void)c;”?

class ArgString : public Arg::Base
{
public:
    ...
    bool CanConvertToInt() const
    {
        const char *cstr = mValue.c_str();
        char *result = 0;
        long d = strtol(cstr, &result, 10);
        (void) d; // what is the usage of this line?
        return result != cstr;
    }

private:
    std::string mValue;
};

Can someone tell me what the purpose of the following line is?

(void) d;

Thank you

// Update //

As some people pointed out, the purpose of the line is to suppress the compilation warning. To me, that is very strange. Because this is much severe warning

    warning C4996: 'sprintf': This function or variable may be unsafe. Consider using sprintf_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.

Why we ignore this big warning and ONLY address the smaller one.

Community
  • 1
  • 1
q0987
  • 34,938
  • 69
  • 242
  • 387
  • I dont know what the purpose is, but it IMHO the statement doesnt produce any effects ;-) – emesx Dec 13 '11 at 16:59
  • Note this is code you have control over, please comment the answer after it. – 111111 Dec 13 '11 at 16:59
  • The warning about `sprintf` is issued by a Microsoft compiler. `sprintf` is a standard C function, and it can be used safely if you're careful. But that's a separate question; there was no `sprintf` call in the code you showed us. – Keith Thompson Dec 13 '11 at 17:14
  • The warning about `sprintf` just appeared within the last couple of years, the code in question was probably older than that and did not generate a warning until you upgraded your compiler. It's a good idea to eliminate all warnings so that when a new one appears, you'll notice it and take action. – Mark Ransom Dec 13 '11 at 17:39

3 Answers3

4

The pattern (void)d is typically done to tell a code analyzer that you are explicitly ignoring the return value of a function. Many C analyzers consider it an error to ignore a return value as it could result in ignoring a failure. This is a way of saying "I meant to do that"

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
3

The only time I've seen something like that is to prevent a warning about an unused variable. Casting something to (void) does absolutely nothing, but it counts as a usage of the variable.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

It avoids an unused variable warning. I've seen this used in assert macros so that in release you don't get unused variable warnings. It evaluates to a no-op.

David
  • 27,652
  • 18
  • 89
  • 138