1

I am using a library that has a path that doesn't set a variable before it is returned, and g++ is giving me a warning about it. Is there a way for me to avoid this warning without changing the library and without disabling the warning?

#include<iostream>

// Begin Library function
inline int foo() {
    int y;
    if( /*something that will always be true*/ ) y = 42;
    return y;
}
// end Library function

void bar(int x) {
    std::cout << x;
}

int main() {
    int x;
    x = foo();
    bar(x);
    return 0;
}
plafratt
  • 738
  • 1
  • 8
  • 14
  • 1
    Can you change `foo`? Or is the problem that a warning appears after inlining into `main`? (If the condition is always true, why check it at all?) – Florian Weimer Oct 24 '19 at 20:12
  • I can't change foo(), as it is in the library. foo() is declared inline. Sorry that the comment in the code is misleading. The condition isn't always true - but in the library where I am seeing this problem, the path through which "y" isn't set is never executed. – plafratt Oct 24 '19 at 20:19

2 Answers2

1

How complex is the condition? In many cases, this will work to suppress such warnings:

if (! (/*something that will always be true*/))
  __builtin_unreachable();
x = foo();

Or, if you build without -DNDEBUG:

assert(/*something that will always be true*/);
x = foo();

This way, when foo is inlined into main, GCC will realize that the condition can never be true, and not warn about the uninitialized value.

Florian Weimer
  • 32,022
  • 3
  • 48
  • 92
  • Unfortunately, the conditional that branches to the path that leaves "y" unset uses protected members, so I can't access those variables from outside of the library. – plafratt Oct 24 '19 at 20:43
  • To make this more concrete - [here](https://github.com/systemc/systemc-2.3/blob/master/src/sysc/communication/sc_fifo.h#L234) is the library, and the function is the `read()` function. The problem is the path that leaves the variable `tmp` unset before `read()` returns `tmp`. But that path should never actually get executed. – plafratt Oct 24 '19 at 20:45
  • I think you also need to provide your source code. I wouldn't rule out an actual bug somewhere. – Florian Weimer Oct 24 '19 at 20:55
  • Ok. I was inclined to think it was a bug, but I noticed that I get this warning with g++ 4.9.2 but not with g++ 6.2.1. – plafratt Oct 24 '19 at 21:01
0

The error I am getting seems to have something to do with the fact that foo() is declared inline, because I found one way around the warning by using this approach: link

int main() {
  int x;
  volatile bool b{true};
  if(b) x = foo();
  else x = foo();
  bar(x);
  return 0;
}
plafratt
  • 738
  • 1
  • 8
  • 14