009.- Curso C++ Básico. Espacios en blanco y formateado de Código.
How to Format Code in C++
Importance of Code Formatting
- A good programmer must understand how to format their code, including the use of whitespace and the placement of function braces.
- In C++, whitespace such as spaces, tabs, and new lines are generally ignored by the compiler, making it a whitespace-independent language.
Compiler Behavior with Whitespace
- The C++ compiler does not consider a statement complete until it encounters a semicolon; thus, statements can be split across multiple lines without issue.
- Exceptions exist where whitespace is significant: text within quotes retains all spaces and cannot span multiple lines without causing an error.
Handling Comments and Best Practices
- Single-line comments end at the line's conclusion; starting a new line will treat subsequent text as code rather than a comment.
- Unlike some languages, C++ allows programmers flexibility in formatting without strict rules.
Recommendations for Indentation and Braces
- There is no strict preference between using spaces or tabs for indentation; however, if tabs are used, they should be set to 3 or 4 spaces.
- Indentation refers to the spacing after an opening brace on a new line. For example, four spaces are recommended between function declarations.
Styles for Brace Placement
- Two acceptable styles exist for placing braces: one places the opening brace on the same line as the declaration (reducing vertical space), while another places it on its own line (improving readability).
- Many programmers prefer placing braces on their own lines for better visibility of code structure and to avoid errors related to mismatched braces.
Line Length and Formatting Tools
- Lines should ideally not exceed 80 characters; if necessary, they can be split into multiple lines at reasonable points.
- Editors often feature guides that indicate character limits visually; plugins can assist in maintaining proper formatting standards.
Utilizing Visual Studio Features
- Modern IDE features allow quick formatting options through menus like "Edit" > "Advanced" > "Format Document."