4️⃣

1.4 Style

 

An Introduction to Coding Style

Before we begin coding, let’s go over some guidelines for how you should set up your code, so it’s easy to read - not just for you, but for everyone who reads your code!

Comments

Programmers use comments to explain what they are doing in their code. Comments are not only helpful for onlookers, but they can also serve as a great tool for you!
 
If you’re working on a program over a stretch of a couple days, it’s easy to come back to where you left off in your code if you have comments explaining what you did in major parts of your code.
 
Don’t worry about what your comments say or if they’re grammatically correct - comments have no effect on your actual code, if used correctly. You can recognize comments in your programs because the color of every comment changes to differ from the other colors of the keywords used in your actual code.
 
Programmers can use single-line comments or multi-line comments, depending on what their comment consists of. These are exactly what they sound like - single-line comments only take up one line in your program, while multi-line comments take up multiple lines.
 
Comments can look a little different from one language to another. In C, single-line comments begin with two forward slashes (“//”) and multi-line comments begin with “/” and end with “/”. Note that single-line comments don’t need an indication of the end of the comment, only multi-line comments do. Here is an example of some sample code:
 
int main(void) { // this is a single line comment /* this is a multi-line comment */ }

Indenting

Another important component of style is indentation. Although white space doesn’t affect the way your program runs, it is still good practice to maintain clean code so it’s easy to read. Do you see the curly braces (“{}”) in the code above? Everything inside curly braces such as those should be indented. To indent something, simply hit the “tab” key on your keyboard once.
 

Curly Braces

There are two ways to correctly place curly braces in your code. Refer to the examples below.
 
Method 1
int main(void) { // code }
Method 2
int main(void) { // code }
 
In the first way, notice how the first curly brace comes right after the header of the main method. In the second way, the first curly brace comes on the next line and it is lined up with the ending curly brace. Both ways of placing curly braces are accepted and indicative of good style.

Previous Section

Next Section

 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.