warning: variable set but not used [-Wunused-but-set-variable]
Solution 1
You need to include the preprocessor guards around the declaration and initialisation of BoolTest
:
test_function()
{
#ifdef CHECK
BOOL BoolTest = test_function2();
#else
test_function2();
#endif
#ifdef CHECK
if (!BoolTest) {
misc_StartErrorReport();
misc_ErrorReport("\n test_function2: Input not indexed.\n");
misc_FinishErrorReport();
}
#endif
(this assumes that you still want to call test_function2()
even if CHECK
is not defined, presumably for its side-effects - if not, then you don't need the #else
section and you can combine the two #ifdef
blocks into one).
Solution 2
Setting a variable is assigning it a value (maybe implicitly)
int main(void) {
int local1, local2;
local1 = 0; /* local1 set to 0 */
local2 = 0; /* local2 set to 0 */
return 0;
}
In the program above, both variables were set to a value but they weren't used. If I replace the second line with
int local2 = local1;
now I have used the local1
variable -- and the warnings should be only 1.
To get rid of the warning, delete the assignment from your code. This may, in turn create other warnings ... :)
Solution 3
It means that you assign a value to a variable, but then you never read that value later in your code (hence the verbage, "set but not used"). For example:
int useful = 10;
int useless = 3;
if (useful) {
//Do stuff
}
Notice that you give both useful
and useless
values, but you only read the value in useful
.
Usually, when I get this message it means that I forgot about a variable or found a way to inline a statement that no longer needs that variable.
Solution 4
With g++ 7.x and higher and clang++ 4.x and higher (using c++11 or higher), as well as with Visual Studio 2017 version 15.3 and later (available with /std:c++17), you can use the standarized [[maybe_unused]] attribute.
For example,
int main()
{
int x [[maybe_unused]] = 5;
}
will not give a warning, not even with -Wunused-variable and the likes.
thetna
I am a guy from Nepal who is very much fond of doing programming.
Updated on June 06, 2020Comments
-
thetna almost 4 years
I have been getting following warning while compiling the C source code in the
gcc 4.6.1
.warning: variable set but not used [-Wunused-but-set-variable]
I refered to this link Wunused but could get exactly what is causing this warning.Would anybody tell me in more details what is causing this warning and how can We get rid of it?
[EDIT] I have a following snippet of code. The compile shows the above mentioned warning. Could you please suggest me how can correct it?
test_function(){ BOOL BoolTest; BoolTest = test_fucntion2(); #ifdef CHECK if (!BoolTest) { misc_StartErrorReport(); misc_ErrorReport("\n test_function2: Input not indexed.\n"); misc_FinishErrorReport(); } #endif // BoolTest is no more used below it. // }