Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

No curly braces?

The code in the Conditionals - If-Else video does not navy curly braces, as it is unnecessary. Why is it unnecessary? Does the compiler treat it any differently in terms of memory allocation? I have heard that C will treat things differently, even if there is a tiny difference. I think one of these tiny things was the difference between "array()" and "array".

Here is the code exactly as it is in the video:

int main()
{
    char a = 'a';
    char b = 'b';
    char g = 'g';

    char letter = 'b';
    if (letter == a) printf("letter %c is %c", letter, a);
    else if (letter == b) printf("letter %c is %c", letter, b);
    else if (letter == g) printf("letter %c is %c", letter, g);

    return 0;

Here is how I would have done it and did do it in Xcode:

int main()
{
    char a = 'a';
    char b = 'b';
    char g = 'g';

    char letter = 'b';
    if (letter == a) {
        printf("letter %c is %c\n", letter, a);
    } else if (letter == b) {
        printf("letter %c is %c\n", letter, b);
    } else if (letter == g) {
        printf("letter %c is %c\n", letter, g);
    }

    return 0;
}

So yeah, is there a difference except for style? Silly question I know, but I want to avoid future issues.

I know, I know, I stress over tiny details.

1 Answer

Curly braces are optional if you only have a single statement within the body if your if statement. You are only required to use curly braces if you have multiple statements within the body of your if statement. The same rule applies for for and while loops when you get to those. Personally, I use curly braces when there is only a single statement within the body to keep things uniform, but that's a matter of your own style.

The compiler will treat it exactly the same whether you use curly braces or not.