author: soymadip
title: "Style Guide: Google"
language:
sid: 1
- Indentation: Use 2 spaces for indentation, not tabs.
- Line length: Limit lines to 80 characters, with exceptions for long lines like URLs or function calls.
- Braces: Use braces for all control flow statements (
if
, for
, while
, etc.), even for single statements or empty blocks.
- Whitespace:
- Use a space between keywords and parentheses (e.g.,
if (x > 0)
).
- No space before or after parentheses in function calls (e.g.,
foo(x)
).
- Use spaces around operators (e.g.,
x + y
), but not immediately before or after parentheses.
- Naming Conventions:
- Variables: Use
lower_snake_case
for variable names.
- Constants: Use
kCamelCase
for constants.
- Functions: Use
CamelCase
for function names.
- Classes/Structs: Use
CamelCase
for class/struct names.
- Block Comments: Use
/* comment */
for block comments.
- Line Comments: Use
// comment
for single-line comments.
- Documentation Comments: Use
///
or /** ... */
for documentation, especially for public APIs.
- Commenting Style:
- Start with a capital letter and avoid ending with punctuation unless it's a question.
- Keep comments clear and concise. Explain "why" something is done, not just "what" is done.
- Files: Each file should contain only one class or functionality if possible. Split large files into smaller ones based on logical units.
- Headers and Implementation Files:
- Use
.h
for headers and .cc
for implementation files.
- Include guards in header files (
#ifndef
, #define
, #endif
).
- Prefer forward declarations over includes when possible in header files.
- Namespacing: Use the
namespace
keyword to define and enclose related classes or functions.
- Exceptions: Prefer exceptions to return codes for error handling.
- Exception Safety: Write exception-safe code to ensure resources are released correctly during exceptions.
- Assert: Use
assert()
for conditions that should never fail in debug builds.
- Smart Pointers: Prefer
std::unique_ptr
and std::shared_ptr
over raw pointers for automatic memory management.
- RAII: Use Resource Acquisition Is Initialization (RAII) to manage resources like file handles and memory.
- Avoid Memory Leaks: Ensure dynamically allocated memory is properly deallocated.
- Prefer standard library containers vector,
std::map
, etc. over raw arrays or home-grown data structures.
- Use
std::unique_ptr
for ownership and std::shared_ptr
for shared ownership.
- Use
const
where applicable to indicate that variables or objects should not be modified.
- For pointer types, use
const
to specify whether the pointer or the data it points to is constant.
- Avoid
using namespace std;
in header files or large code blocks to prevent name clashes.
- Limit macros: Prefer constants or inline functions over macros.
- Type safety: Prefer static and dynamic type checking over casts (e.g., avoid
reinterpret_cast
unless necessary).