Adding statements inside curly braces change the code functionality?

Viewed 99

I am fairly new to C++, I am trying to replicate a code from C++ reference that turns spaces in a string to dashes. Here's the code

void sp_to_dash(const char *str){
    while(*str){
        if(*str==' ')
            cout<<("%c", '-');

        else
            cout<<("%c", *str);
            str++;

    }
}

int main(){
    sp_to_dash("hello world how are you");
    int j;
    cin>>j;
    return 0;
}

Now this works perfectly, the output I get is OUTPUT: hello-world-how-are-you

However when I enclose the code in sp_to_dash function in curly braces like this

void sp_to_dash(const char *str) {
    while (*str) {
        if (*str==' ') {
            cout << ("%c", '-');
        } else {
            cout << ("%c", *str);
            str++;
        }
    }
}

The output I get is an infinite loop of dashes, I don't understand why that is, Can anyone explain to me why adding code in curly braces like this triggers an infinite loop?

2 Answers

The indentation is misleading. There can only be a single statement under an if or else branch. To put several, it must be a compound statement (in curly braces). So this

    else
        cout<<("%c", *str);
        str++;

... is equivalent to this

    else
        cout<<("%c", *str);
    str++;

So adding the curly braces changes the programs flow of control, which is why you get different behavior. Many (possibly most) would recommend to always add curly braces, even on single statement branches, to future proof it.

Probably the az indentation is confusing. Without braces only the first line is executed and str++ is not intended to be part of branch else but be executed in every cycle. In the second case the str is increment ed only venue the current character is not '-' which is true at the end.

Furthermore it will continue reading the memory after it reached the end of the string. This menory area belongs to other variable or maybe other process this it can be handled as random characters from your perspective.

Related