std::string s="s1";
std::cout<<s<<std::endl;
{
	std::string s="s2";
	std::cout<<s<<std::endl;
};

Why can I have two variables with the same name existing like this?

it is becoz of the scope of the variable
one declare out side the function is in the Global Scope
and other one is inside the Function having the Function Scope
...
now how question is if the variable name is same then... how does it works...
Answer is ...
by help of scope operator(i am not sure it is operator or not sorry to say i forgot) "::"
if the variable is in the global scope the ::<variable>
if there is no ambiguity in the name of the variable then the scope resolution operator is not need ...

this thing comes handy in class..

Where's the function? Wouldn't the {}s be ignored since there is no function or if statement or control loop associated with the {}s to generate a new scope?

AFAIK brackets can be used without any function or if statement, simply as code-block.
They just come in handy for functions, classes, etc.

Where's the function? Wouldn't the {}s be ignored since there is no function or if statement or control loop associated with the {}s to generate a new scope?

ya ya, thanx for correcting...

>>AFAIK brackets can be used without any function or if statement, simply as code-block.
They just come in handy for functions, classes, etc.

That would be interesting.

>>AFAIK brackets can be used without any function or if statement, simply as code-block.
They just come in handy for functions, classes, etc.

That would be interesting.

I'm stunned. Can somebody tell me if bracket section alone is by C/C++ standard?
Because, DevC++ mingw and Visual C++ Express 2008 both compile and execute properly:

#include <iostream>

int main(){
    int a=5;
    std::cout<<"Out of bracket:"<<a;
    {
        int a = 6;
        std::cout<<"\nIn bracket: "<<a;
    }
    std::cout<<"\nOut again: "<<a<<std::endl;
    
    std::cin.get();
    return 0;
}

Providing output:

Out of bracket: 5
In bracket: 6
Out again: 5

Maybe it's one of those things like it's valid to use OR instead of || or AND instead of &&, or that a comma is an operator, etc. But, yeah, it would be interesting if those who have access to a copy of the standard or know the relevant section of the standard would post a report.

This article has been dead for over six months. Start a new discussion instead.