Learn to code in C++ (lesson 3) - comments

in steemiteducation •  9 months ago

You should now have a pretty good handle on outputting text to your display. But before we move onto "bigger things", we quickly need to touch on comment statements.

Comment statements are any statements that begin with //. When C++ sees //, the compiler with automatically ignore everything after the // on that line.

You might be wondering why you would want to include any "code" that is totally ignored. Well, remember when we spoke about good programming style? It is good practice to include comments in your program explaining what the program does (or even what parts of your program do).

As an example, it is best practice to include a comment statement at the whole beginning of your program letting another programmer know what the program actually does. Like this:

//Display "Hello World" on the screen
#include <iostream>
using namespace std;

int main() { cout << "Hello, World!"; return 0; }

Going forward, make sure that you use a comment statement at the beginning of all your programs explaining the purpose of your program.

Remember, everything after the // on that line is ignored. Take this program as an example:

//Display text on different lines
#include <iostream>
using namespace std;

int main() { cout << "Line 1" << endl; cout << "Line 2"; return 0; }

The output would be:

Line 1
Line 2

Now we add // before the first cout statement:

//Display text on different lines
#include <iostream>
using namespace std;

int main() { //cout << "Line 1" << endl; cout << "Line 2"; return 0; }

Now the first cout statement is totally ignored thus the output would be:

Line 2

I hope you understand the importance of comments statements and how useful they can be. You will see that we will be using these a lot as our programs start to grow 😎

Interested in additional content, including activities and solutions?
See my blog here.

Team South Africa banner designed by @bearone

Please upvote if you liked this post, follow if you want to see more, and let me know your thoughts in the comments.

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Yeah I certainly do understand the importance of comments. I'm learning Matlab this semester in school my instructor uses comments and it really helps me understand what he did on his code. Thanks for sharing can't wait to learn more.


I'm glad you're enjoying the programming world 😁
Thanks for checking out my post 😎

You just received a Tier 0 upvote! Looking for bigger rewards? Click here and learn how to get them or visit us on Discord