Always mark variables, parameters, and methods as `const` when they don't modify state. This improves code safety, enables compiler optimizations, and makes intent clearer to readers.
Always mark variables, parameters, and methods as const
when they don’t modify state. This improves code safety, enables compiler optimizations, and makes intent clearer to readers.
Apply const in these scenarios:
const auto* command_line = base::CommandLine::ForCurrentProcess();
bool IsDetachedFrameHost(const content::RenderFrameHost* rfh)
bool IsWirelessSerialPortOnly() const;
const display::Screen* screen = display::Screen::GetScreen();
Example transformation:
// Before
auto* command_line = base::CommandLine::ForCurrentProcess();
display::Screen* screen = display::Screen::GetScreen();
bool IsDetachedFrameHost(content::RenderFrameHost* rfh);
// After
const auto* command_line = base::CommandLine::ForCurrentProcess();
const display::Screen* screen = display::Screen::GetScreen();
bool IsDetachedFrameHost(const content::RenderFrameHost* rfh);
Const correctness prevents accidental modifications, enables the compiler to catch errors early, and serves as documentation of your code’s intent. When in doubt, start with const and remove it only if modification is necessary.
Enter the URL of a public GitHub repository