unidentified blocks?

Hi

I would be thankful if you answered this question of mine:

what does such a structure mean?

... // codes
{
... // codes
}
{
... // codes
}
... // codes


doe these blocks mean anything special or are they just to help the coder divide different parts of the code?

Thanks a lot

Soheil
They make a new scope. At the end of the scope, objects that were in it are deleted:
1
2
3
4
5
6
7
8
9
10
int main()
{
  int a = 5;
  {
    int b;
    cin >> b;
    a += b;
  } //b is no longer available in memory or in scope
  cout << a;
}


This is useful for when you want to allocate a lot of memory for something without using new, and then delete it later in your code so it doesn't spend the entire rest of the application using memory it doesn't need.
closed account (zb0S216C)
I never knew that you could do that. That could come in handy some day.

I guess you could do this to make it easier to read:

1
2
3
4
5
6
7
8
9
#define SCOPE_BEGIN  {
#define SCOPE_END    }

int main( )
{
    SCOPE_BEGIN
        // ...
    SCOPE_END
}

Wazzak
Last edited on
That seems to be to be rather a lot of extra typing to me ^^

PS: Do you write your signature every time, or auto-insert it somehow?
closed account (zb0S216C)
Xander314 wrote:
Do you write your signature every time, or auto-insert it somehow?

I'm not the only one who used a signature. I write mine manually as it only takes a couple of seconds.

Wazzak
Last edited on
It's just you and Albatross isn't it? Yours is twice as long as hers so I just wondered...

I might give myself one, as some members are finding our high Xander density confusing.
Interesting! Yes, it seems it could be very useful. Thank you guys a lot for your help.
Could also be useful for forcing a deconstructor. And when using boost.thread you can use a scoped lock within a local scope like that to work like a critical section.

Like this, for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
boost::mutex iomutix;

void ThreadA()
{
	// other code
	{
		boost::mutex::scoped_lock lock(iomutex);
		cout << "In ThreadA" << endl;
	}
	// other code
}

void ThreadB()
{
	// other code
	{
		boost::mutex::scoped_lock lock(iomutex);
		cout << "In ThreadB" << endl;
	}
	// other code
}

int main()
{
	boost::thread thrdA(&ThreadA);
	boost::thread thrdB(&ThreadB);

	thrdA.join();
	thrdB.join();

	return 0;
}
Last edited on
Topic archived. No new replies allowed.