Reputation: 65
The following code is for replacing multiple consecutive spaces into 1 space. Although I manage to do it, I am confused in the use of curly braces.
This one is actually running fine:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ch, lastch;
lastch = 'a';
while((ch = getchar())!= EOF)
{
if(ch == ' ')
{
if (lastch != ' ')
putchar(ch);
}
else
putchar(ch);
lastch = ch;
}
}
But I can't figure out why this one isn't, by only putting curly braces within the inner loop and else statement:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int ch, lastch;
lastch = 'a';
while((ch = getchar())!= EOF)
{
if(ch == ' ')
{
if (lastch != ' ')
{
putchar(ch);
}
}
else
{
putchar(ch);
lastch = ch;
}
}
}
Can I not enclosed a loop within a loop with curly braces? I've read that the second one would be a good practice to make it readable, but what am I doing wrong?
Upvotes: 2
Views: 252
Reputation: 227370
The only difference between the two is the scope of the else
. Without the braces, it spans until the end of the full statement, which is the next ;
, i.e the next line:
else
putchar(ch); /* end of else */
lastch = ch; /* outside of if-else */
With the braces, it covers the lastch
assignment too.
The same applies to the if
statement, but there you have a single line so it makes no difference.
Upvotes: 8
Reputation: 310993
Any control structure (if
, else
, for
, while
, etc.) operates on a block of code. Blocks are usually denoted by curly braces ({}
), but if those are omitted, a single statement acts as the block. Note that unlike in Python, for example, indentation has no meaning in C, it's just a convince to make the code more readable.
Having said that, let's examine your else
block:
else
putchar(ch);
lastch = ch;
Since there are no curly braces here, this block is actually equal to the following:
else
{
putchar(ch);
}
lastch = ch;
And not to the block in your second code snippet. Here, the indentation of lastch = ch
did help us understand the code, it was confusing due to bad indentation that made it seem as though it was part of the else
block when in fact it was not.
Upvotes: 3