3

Is there any functional difference between marking a virtual method's unused parameter arguments with GCC's __attribute__((unused)) and casting the argument to (void)?

class Other {
    virtual int sum(int a, int b, int c);
};

class Example : Other {
    virtual int sum(int a, int b, int c __attribute__((unused))) override {
        return a + b;
    }
};

class Example2 : Other {
    virtual int sum(int a, int b, int c) override {
        (void)c;
        return a + b;
    }
};

Both do the job of silencing unused argument warnings and neither of them warn, if the variable is used later. Though the GCC __attribute__ is longer.

JaMiT
  • 14,422
  • 4
  • 15
  • 31
ktb
  • 1,498
  • 10
  • 27

1 Answers1

4

There is no functional difference, as both may result in no-operation. (void) casting has an upper-hand as it works in all the platforms.

Another approach is to use a macro to silence such arguments. So when you disable the macro, you will know all the unused parameters in your code.

#define UNUSED(X) (void)X 

However in this specific scenario, I would prefer simply not to mention the unused argument. It assures the future reader of the code that the unmentioned argument is guaranteed to be not in use.

int sum(int a, int b, int /*c*/) override {  // comment is optional
  return a + b;
}
iammilind
  • 68,093
  • 33
  • 169
  • 336
  • 1
    Just to be clear, this does not work for C. – ktb Nov 21 '19 at 03:34
  • 1
    @ktb You tagged the question "C++", so why would an answer bring up a different language? – JaMiT Nov 21 '19 at 04:33
  • @JaMiT "Just to be clear". Less info in never better. – ktb Nov 21 '19 at 04:52
  • @ktb I disagree. But just to be clear, this does not work for Assembly, AWK, Bash, BASIC, ECMAScript, Lisp, Logo, Lua, Mathematica, MUMPS, NWScript, Pascal, PHP, sed, SQL, TeX, and XSLT. Does this information add value to this answer? I think not. If the information is just noise, then less is better. – JaMiT Nov 21 '19 at 06:12
  • @JaMiT The code base in question has C in it too, realized I didn't put it in the tags. – ktb Nov 21 '19 at 17:03
  • 1
    @ktb it does not matter as it `override` will not "work" as well in C. – 0___________ Nov 21 '19 at 17:07
  • 1
    @ktb From the right perspective, the code base might have some C in it, but it is definitely not C. To convert the question's code to C, you have to change `class` to `struct` and get rid of both inheritance and member functions. This leaves you with `struct Other {};`, which does not illustrate the question you asked. – JaMiT Nov 21 '19 at 23:18