Ok, I am sort of new to C++, and I just came across something that I don't fully understand.

int main(){
int iX=5;

{
int iY=30;
std::cout<<iY<<std::endl;
}

std::cout<<iX<<std::endl;
return 0;
}

What does it mean when I make a code block with no if,else etc..? Does it just make the variables inside local to that block? How would you use this?

Thanks.

Recommended Answers

All 3 Replies

You are correct. When you create an independent block, such as that in Lines 4 - 7, the variables are local to that block. Any variable that is created within that block goes out of scope and is destroyed when the block ends, unless it was dynamically allocated.

Alarm bells should be going off at this point. If you're going to use dynamic allocation within the block, you better make sure that either the pointer isn't defined within that scope or that you de-allocate the memory before the end of the block. If you don't, you'll have a memory leak because you'll lose your pointer to the allocated memory and the memory won't be de-allocated.

I personally don't use it all that often, but others probably do more frequently. Generally, I would use it if I need a temporary variable to hold some information and want to conserve resources. That way, the memory associated with the variable is only allocated for as long as you need it. It's a little bit of a stretch, because there is a big difference, but I suppose that you could go so far as to call it a type of dynamic memory.

How would you use this?

It's less useful in C++ than C89, where all variables must be declared at the beginning of a block. Though unnamed blocks are useful if you want to force a shorter lifetime on resource intensive objects:

// Lots of code

{
    ResourceIntensive ri(...);

    ri.do_stuff();
} // ri is destroyed here rather than taking up resources unnecessarily

// Lots of code

Interesting, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.