15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

278<br />

Adding Comments to Source Code<br />

SECTION .text<br />

global main<br />

main:<br />

mov eax,4;<br />

write system call<br />

mov ebx,1<br />

mov ecx,msg<br />

mov edx,len<br />

int 0x80<br />

mov eax,1 system call<br />

mov ebx,0<br />

int 0x80<br />

You could replace the preceding assembly language commands with a<br />

shorter, more descriptive high-level language command like this:<br />

PRINT “It’s alive!”<br />

Such self-documenting code helps explain what a single line of code does,<br />

but doesn’t necessarily tell you how the entire program works as a whole or<br />

what problem the program even solves.<br />

Rather than rely on “self-explanatory” language commands, programmers<br />

started adding explanations directly into the source code itself by using<br />

comments.<br />

A comment is nothing more than text, embedded in the source code. To keep<br />

the compiler from thinking a comment is an actual command, every comment<br />

needs a special symbol in front of the comment, such as<br />

REM This is a comment in BASIC<br />

‘ This is another comment in BASIC<br />

// This is a comment in C++ and Java<br />

# This is a comment in Perl and Python<br />

; This is a comment in LISP and assembly language<br />

Comments allow you to write short explanations, directly in the source<br />

code, that describe what the source code does. Looking at the following<br />

code, can you understand what it does?<br />

C = SQRT(A * A + B * B)<br />

Deciphering this code is straight<strong>for</strong>ward. This command multiplies two variables<br />

by themselves, A and B, adds the results together, and finds the square<br />

root of the sum, which gets stored in the C variable. However, knowing how<br />

the command works doesn’t tell you what or why this code is doing this. By<br />

adding comments to the source code, you can explain this, as follows:<br />

‘ Calculates the hypotenuse of a triangle (C)<br />

‘ using the Pythagoras theorem: C 2 = A 2 + B 2<br />

C = SQRT(A * A + B * B)

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!