I am processing test.c file and trying to count single line comments in it.
When I spot two consecutive / characters, I set slc trigger to true.
And when I reach the end of line, I need to set slc trigger to false.
Of course \n character clearly indicates the end of single-line comment.
switch (character)
{
case '\n':
slc = false; // single-line comment ended
break;
But when \n character found, slc could be either true or false.
switch (character)
{
case '\n':
if (slc) slc = false; // single-line comment ended
break;
Is there any difference between these two code blocks?
How should I write?
Use the first form. Adding an extra
ifcheck which doesn’t affect the functionality of your code, only its readability, is bad practice. You should always write the most concise way possible that doesn’t obfuscate the intention of your code. Since in this case your intention is always for the variable to befalse, simply setslc = false.