Thread: Is this usefull? {}

  1. #1
    Registered User mikahell's Avatar
    Join Date
    Jun 2006
    Posts
    114

    Is this usefull? {}

    I found out that I could put "{ }" around my code when there isn't any function, conditions, etc, attached to it. I mean that I can succesfully compile such a code:

    Code:
    int main()
    {
    	int a = 1;
    	{
    		int b = 1;
    	}
    	//b is unknown here...
    	//a is known here...
    	return 0;
    }
    Well, so you see I mean the inner set of "{ }", there isn't any function or condition to it such as "main() {}" but though, declarations in that inner "body" of the "main" are scoped so I can't access them outside of that inner "body"... I don't know if this as a usefullness, or if this is just a flaw in the compiler (MSVC++) but I don't see how it could be usefull.

    I also tried to see if I could place "break" statement inside of it, to get directly to the end of the inner {}, but it doesn't work, as there is no loop or switch...

    Any clue to this special thing?

  2. #2
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446
    It has its uses, yes. And it is definitely not a "flaw". It is part of the programming language.

    It's a way to introduce new scopes into the current one. You can also nest them. Its uses are varied. Some better than others. You may want to shadow certain identifiers temporarily by redeclaring them inside the new scope. Once one leaves the scope, the former name gets back into view. Or maybe you want to introduce new names that you don't want to be visible across the entire scope...

    Do remember that statements like if, switch, while, for, ... also introduce a new scope. You can see part of its usefulness there.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  3. #3
    Register User andor's Avatar
    Join Date
    Aug 2006
    Location
    Novi Sad
    Posts
    42
    It's not a compiler flaw it's legal. In C is not legal to declare a variable in a middle of the function like in C++. So in C you can declare it with
    {
    int i;
    // some action which uses variable i but it will not needed elsewhere
    }
    This is left in C++ from C.

  4. #4
    Registered User
    Join Date
    Oct 2004
    Posts
    151
    They can also be taken advantage of for some very silly constructs:
    Code:
    #ifdef DEBUG
    if (!debug)
    #endif
    {
            something();
            something();
    }
    System: Debian Sid and FreeBSD 7.0. Both with GCC 4.3.

    Useful resources:
    comp.lang.c FAQ | C++ FQA Lite

  5. #5
    Registered User mikahell's Avatar
    Join Date
    Jun 2006
    Posts
    114
    Yes, but I thought I could use them for something like this:

    Code:
    {
    	if (/*something is true*/) break; //just to leave this "{ }" inner place...
    	if (/*another thing is true*/) break;
    	if (/*another something is true*/) break;
    	//...
    	//Do something
    }
    I don't know, but if it would work, we could use breaks so we can someway filter out values to do something if all was as expected, or just try to invent something that almost looks like a switch. (But then why not using the already built-in switch...)

  6. #6
    Registered User
    Join Date
    Oct 2004
    Posts
    151
    Why on earth would you do that instead of just using an else clause and disjunction? And if you were dead-set on using break, you could have a do...while(0) loop for just 10 extra bytes.
    System: Debian Sid and FreeBSD 7.0. Both with GCC 4.3.

    Useful resources:
    comp.lang.c FAQ | C++ FQA Lite

  7. #7
    Useless Apprentice ryan_germain's Avatar
    Join Date
    Jun 2004
    Posts
    76
    Quote Originally Posted by mikahell
    Yes, but I thought I could use them for something like this:

    Code:
    {
    	if (/*something is true*/) break; //just to leave this "{ }" inner place...
    	if (/*another thing is true*/) break;
    	if (/*another something is true*/) break;
    	//...
    	//Do something
    }
    yes you could use it like that but it's not really what it's for since it will just leave the if in the next line anyways. Maybe a more appropriate place for a break would be a while loop or something. Also try using if...else if....else.

    [EDIT] actually you should really only try to use break statements with a switch.

    Code:
    switch (control_expression)
    {
        case constant1:
            statement_sequence1
            break;
        case constant2:
            ...
    }
    the break here will stop the code from going into the next case by exiting the {}
    Last edited by ryan_germain; 08-14-2006 at 06:31 AM.
    There is not the slightest indication that [nuclear energy] will ever be obtainable. It would mean that the atom would have to be shattered at will.

    -Albert Einstein, 1932

  8. #8
    Registered User mikahell's Avatar
    Join Date
    Jun 2006
    Posts
    114
    Why on earth would you do that instead of just using an else clause and disjunction? And if you were dead-set on using break, you could have a do...while(0) loop for just 10 extra bytes.
    That's a good idea!

  9. #9
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >I don't know if this as a usefullness
    Yes, it does. In C++, the best use of this feature, imo, is to create a smaller scope so that visibility is limited and destructors will be called. For example, let's say that I want to dump to a file but the fstream object should not be readily accessible:
    Code:
    #include <fstream>
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main()
    {
      vector<string> v;
    
      // A lot of code here, file stream does not exist
    
      {
        ofstream out ( "somefile" );
    
        if ( out.is_open() ) {
          vector<string>::iterator it = v.begin();
          vector<string>::iterator end = v.end();
    
          while ( it != end )
            out<< *it++ <<"\n";
        }
    
        // file stream goes out of scope here; file is closed
      }
    
      // More code here, file stream no longer exists
    }
    Of course, there's a fine line here. A function might be better suited, so you probably won't see the feature used often.
    My best code is written with the delete key.

  10. #10
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715
    I have also one question similar to this topic.
    I use to write code as follows:
    Code:
    while (test)
    {
        int x;
        ...
    }
    However my friend says that is pretty inefficient way and that variable should be declared before while loop because of performance issue. He thinks it's a lot faster that way because x is newly created and destroyed with each iteration. I must say I agree but didn't actualy try to measure how big this performance issue reall is...
    Gotta love the "please fix this for me, but I'm not going to tell you which functions we're allowed to use" posts.
    It's like teaching people to walk by first breaking their legs - muppet teachers! - Salem

  11. #11
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >However my friend says that is pretty inefficient way
    Tell your friend that 1) 9 times out of 10 he's full of crap and 2) he should stop worrying about trivial things like that.

    1) Most compilers aren't stupid. I would be surprised if any modern compiler failed to optimize your example into a single allocation.

    2) Micro optimizations are rarely needed. Yes, you should keep such things as instruction count and weight in mind, but more often it's the algorithm and good use of caching that will have noticeable effect on performance.
    My best code is written with the delete key.

  12. #12
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    I find them usefull when using switch statements.

    Code:
    switch ( something )
    {
    	case whatever:
    		// do something with something
    		break;
    
    	case whatever2:
    		int variable; // <- EDIT - this is bad
    		break;
    
    	case whatever3:
    	{
    		int variable; // <- No prob here I think.
    	}
    }
    Last edited by twomers; 08-14-2006 at 03:35 PM.

  13. #13
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    twomers: It is allowed. It's also a very bad idea, because the initialization code might be jumped over. Or in other words, there are places where the variable is visible, but it might not have been initialized.
    Yes, simple scopes can be useful for switches when you need case-local variables. Still, often it's better to avoid that and call a function instead. Not always possible, but when possible it's usually the better option.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  14. #14
    pwns nooblars
    Join Date
    Oct 2005
    Location
    Portland, Or
    Posts
    1,094
    Well due to 'things' not being destroyed untill they are out of scope... I have used them to do some caclulations that take a fairly large number of variables then just assign the result to a variable that was outside of scope and the rest (IE 100 int arrays and what not) go out of scope and the memory is freed. Since it was only one time in the program that I needed it, it was either do it that way, or use an inline so that I don't have to sacrifice speed (less moving to and from registers, atleast from my understanding)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Usefull function finding form
    By Yarin in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 11-30-2007, 10:29 PM
  2. debugging
    By St0rM-MaN in forum Tech Board
    Replies: 13
    Last Post: 07-06-2007, 02:03 PM
  3. Usefull Library
    By Thantos in forum Networking/Device Communication
    Replies: 0
    Last Post: 03-04-2004, 09:49 PM
  4. First (semi) usefull program. Big accomplishment for me.
    By imortal in forum C++ Programming
    Replies: 1
    Last Post: 05-03-2003, 12:07 PM
  5. FAQ: Someone know where to use "continue"
    By Vber in forum FAQ Board
    Replies: 55
    Last Post: 12-10-2002, 10:02 AM