I dont understand the { } braces...

I'm a begginer at c++ and I dont understand the { and } braces. They do not follo a specific rule. It seems very random to me. I've seen code like this...

#include
int main()
{
int thisisanumber;
cout<<"Please enter a number:";
cin>>thisisanumber;
cout<<"You entered: "<<thisisanumber;
return 0;
}

and there is also stuff like this...

#include <iostream.h>
int main() //Most important part of the program!
{
int age; //Need a variable...
cout<<"Please input your age: "; //Asks for age
cin>>age; //The input is put in age
if(age<100) //If the age is less than 100
{
cout<<"You are pretty young!"; //Just to show it works
}
else if(age==100) //I use else just to show an example
{
cout<<"You are old"; //Just to show you it works...
}
else
{
cout<<"You are really old"; //Executed if no other statement is executed
}
return 0;
}

how come in the first one everything is in 1 { and } but then in the second one it's all broken up. Will someone please explain this to me? And please go into more detail then just, "they divide functions." thx a bunch.

Comments

  • They follow a very specific rule. They hold blocks of code, however they in and of themselves don't really DO anything, however they are necessary syntacticly.

    If you have experience with BASIC or Pascal then they serve the same function as the begin/end pairs. Even if you don't you should see what they do from the following example...

    [code]
    //not C/C++ code
    function main() begin
    //code for main here
    end

    function myfunc() begin
    if x=5 then begin
    y=10
    z=11
    end
    end
    [/code]

    The {}'s just have the same function as the begin and end pair. They are just a grouping construct. They are necessary as you can imagine how is the compiler supposed to know where to stop grouping code together? For example,

    [code]
    int main()
    x=5;
    y=10;
    z=14;
    [/code]

    How is the compiler supposed to know where main ends? Putting braces around any or none of those lines would be valid.

    "We can't do nothing and think someone else will make it right."
    -Kyoto Now, Bad Religion

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion