Reza Amani
Reza Amani

Reputation: 105

How to suppress the compiler warning on unused variable in C?

For a peripheral requirement in an embedded system, I have to declare a variable to read a register, but won't use the value later. Hence, I get compiler warning about my unused variable naturally. How can I suppress the warning? I have 2 ways in mind:

  1. using compiler directives, I hesitate because they are compiler-dependent
  2. adding a dummy read from variable, like:

    volatile int var;
    
    var = peripheral_register;
    
    var = var;
    

Do you have a better idea?

Upvotes: 7

Views: 3724

Answers (3)

Clifford
Clifford

Reputation: 93476

If all you need to do is read the register (to clear some status flag for example), then you do not need a receiving variable at all just:

(void)peripheral_register ;

is sufficient assuming the register is itself is declared volatile so that it must be read.

Otherwise you could make your dummy var global with external linkage - that way the compiler cannot determine that it is not read elsewhere; but that's a far uglier solution.

Upvotes: 9

Darshan b
Darshan b

Reputation: 157

Define a macro as

#define unused(x) ((void)x)

if peripheral_register is the unused variable the just invoke the macro as unused(peripheral_register). This will remove the warning.

Upvotes: 3

Lundin
Lundin

Reputation: 213809

Your variable is used. Reading a volatile variable is a side-effect.

If you get a compiler warning, I would strongly suspect that your compiler does not conform to the C standard. You should disassemble to code to ensure that the read actually takes place. If not, your compiler is broken beyond repair.

That being said, you can cast any expression to (void) to silence compiler warnings, for example (void)var;. But you shouldn't need to do that in this case.

Upvotes: 2

Related Questions