Are you confused about when to use the semicolon and when not to. Here is a small explanation to make your concept clear.
Roughly speaking semi colons terminate. It tells the compiler that one statement is over.
E.g.
int i; // This statement will declare an integer variable named 'i' terminated with semi-colon
i=10; // This is a statement to assign the value terminated with semi colon
Exceptions
1.Semi-colons are used when setting up a "for"
loop -
the syntax is "for(...;...;...)",
though their main use is to end statements.
2. Note that an "if",
"while" or "for" statement doesn't end straight after the
test condition, they have the block statements to execute if the test condition is true/false/
E.g
if(x>5) // this is not the end of statement there are more statement(x) to be executed if the condition is
true
cout << x; // this statement is executed if the condition is true and is terminated
It's not illegal to put a semi-colon there, but it's rarely
what you want.
E.g. for(i=0;i<5;i++); // this loop has no block statement
Remember we used this kind of loops for getting string length.
char str[100];
cin>>str;
for(int i=0;str[i]!='\0';i++);
cout <<i; // this will display string length. As we had only counting to be done we do not have any other
block statement.
3. Semi-colon to terminate structure or class definitions.
struct POINT
{
int x,y; // end of statement
}; // end of structure
4. Semi-colon to terminate function prototype
Function prototype is function declaration done to tell the compiler about the function return type, type and number of parameters.
Try reading
http://www.cpptalk.net/confused-about-the-meaning-of-the-semicolon-vt11965.html
No comments:
Post a Comment