Making the Compiler Do the Work
Compilers have lots of options that affect the compilation. So far,
with g++
we’ve just been using -o
to name the executable. But
we can also have the compiler warn us about problematic C++ code we may
have written. A useful set of options is:
g++ -Wall -Wextra -Wshadow -Wpedantic
Here’s a brief summary:
-Wall
: this turns on options that warn about things most users deem problematic.-Wextra
: enabled additional warnings that most people think are good to check for.-Wpedantic
: makes sure that you conform to the language standard and not rely on any extensions that the compiler might support.
Here’s an example of a case of using the wrong type in a loop that can be caught with these flags:
#include <array>
int main() {
std::array<double, 10> x;
for (int i = 0; i < x.size(); ++i) {
x[i] = i;
}
}
Here’s an example of catching unused variables:
int main() {
int x, y, z;
x = 1;
y = x * 2;
}
Here’s an example of catching a fallthrough in a switch
statement:
#include <iostream>
#include <cmath>
int main() {
double x{};
std::string sign{};
std::cout << "enter a number: ";
std::cin >> x;
const auto sgn = static_cast<int>(std::copysign(1.0, x));
switch (sgn) {
case -1:
sign = "negative";
case 0:
sign = "none";
break;
default:
sign = "positive";
}
std::cout << "sign = " << sign << std::endl;
}