Reputation: 17268
I have some code performing a summation (below). It is called from another file. However, sum
was not initialized, caused a bug but GCC (v11.1) did not give a compiler error.
I have these flags set:
-Wall -Wextra -pedantic -march=native -Werror=return-type -Wswitch-enum -Wconversion -Werror=attributes -Werror=unused-variable -Werror=unused-parameter -Werror=unused-result -Werror=address -Werror=unused-function -Werror=unused-but-set-parameter -Werror=uninitialized -g -O0
Why did I not get an error for this uninitialized local variable/what flag do I need to set?
Are there any other useful flags I should set? (I'm aware of switch-enum
)
Code:
#include <unordered_set>
#include <concepts>
template<typename T>
concept arithmetic = std::integral<T> or std::floating_point<T>;
template<typename T> requires arithmetic<T>
struct Stat
{
T calculate()
{
T sum; // Not initialized, caused a bug. Compiler gave no error
for(const T& t : m_set)
{
sum += t;
}
// Do other calcs
return sum;
}
// Other methods
std::unordered_set<T> m_set;
};
Upvotes: 1
Views: 1386
Reputation: 58673
Three things:
GCC's uninitialized variable warnings don't work well unless you enable optimizations (-O, -Og, -O2, -O3, -Os
, etc). This is documented (see -Wmaybe-uninitialized
): "These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables." See also GCC - no warning about an uninitialized array with -O0
In general, 100% reliable detection of uninitialized variables is impossible (halting problem). So in some sense, be glad when a compiler does warn you, but you really oughtn't to complain too hard if it doesn't, or if it warns about code that is actually fine. Runtime tools such as valgrind are a good supplement (though still won't always catch everything).
The function has to actually be referenced (either used in this source file or visible externally), otherwise the compiler won't actually compile it and in particular won't check for uninitialized variables, not even with optimization enabled. So compiling this source file all by itself will not cause any warnings.
Upvotes: 4