Sign in to follow this  

small program in C++

This topic is 3842 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

can someone tell me how can the following program work/compile? those inner brackets in the function make no sense to me.
#include <iostream>

using namespace std;

void abc (char &x1, char &y1)
{
	char x;
	x=y1;
	cout<<endl<<x<<x1<<y1;
	{
		char x='T';
		x++;
		(x1)++;
		cout<<endl<<x<<x1<<y1;
	}
	cout<<endl<<x<<x1<<y1;
}

main()
{
	char x='A', y='B';
	abc(x,y);
	cout<<endl<<x<<y;
}

//output:  
//ab pb ub bb

Share this post


Link to post
Share on other sites
Generally it helps if you say what the exact problem is. For instance, by copy and pasting the error messages you received after trying to compiling. Or if the program compiled successfully, what happened and what did you expect to happen when you ran the program?

Anyway, before 'main()' add 'int'. Main requires int as a return type in c++. If you need more help, give a better description of your problem.

Share this post


Link to post
Share on other sites
i am sorry, i was in a hurry...

nothing is wrong with the program per se, but i _do not understand_ the inner brackets that are located within the function.
what is the purpose of those brackets and why does it compile?

Share this post


Link to post
Share on other sites
They create an inner or nested scope. They're perfectly legal, that's why it compiles.

You can nest brackets as much as you want; each pair delimits a new scope for identifiers. In this case, for example, the 'x' in the innermost scope hides the 'x' in the outer scope, and the innermost scope's x is destroyed when execution leaves the scope.

They're not very common, although they're sometimes used to force destruction of automatic variables prior the end of the function, which occasionally has some use.

Share this post


Link to post
Share on other sites
The brackets inside of the function create a new scope which has a char x variable that is set to the value 'T'. This x variable is only valid inside the brackets and is different than the x variable that is declared outside of the brackets.

Also, your output seems to be wrong. Running this in VC 2005 I get

BAB
UBB
BBB
BB

which is what I would expect when looking at the code.

Share this post


Link to post
Share on other sites

This topic is 3842 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this