Coding style

This is a discussion on Coding style within the A Brief History of Cprogramming.com forums, part of the Community Boards category; Having been previously learning C I have recently swapped to C++. What i've noticed is that in C the tendancy ...

  1. #1
    The Earth is not flat. Clyde's Avatar
    Join Date
    Mar 2002
    Posts
    1,420

    Coding style

    Having been previously learning C I have recently swapped to C++.

    What i've noticed is that in C the tendancy was to declare variables at the top of the program, in the book i'm reading on C++ (Accelerated C++ -Practical Programming by Example) they seem to always declare their variables the line before they are used.

    Is it bad to declare variables in the C-style IE. all of them at the top when programming in C++?

  2. #2
    Intranasal Heroin User Xterria's Avatar
    Join Date
    Sep 2001
    Location
    Buffalo, NY
    Posts
    1,035
    you mean as global variables?

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >What i've noticed is that in C the tendancy was to declare variables at the top of the program
    Not a tendency, a requirement. In C all variables must be declared at the beginning of the given block, otherwise it's a syntax error. C++ removes this requirement and variables can be declared anywhere as long as they are declared before they are used.

    -Prelude
    My best code is written with the delete key.

  4. #4
    The Earth is not flat. Clyde's Avatar
    Join Date
    Mar 2002
    Posts
    1,420
    "you mean as global variables?"

    No, i just mean declaring them the first line after "int main()".

    "C++ removes this requirement and variables can be declared anywhere as long as they are declared before they are used"

    And it's good practice to take advantage of this? It's just I find when writing programs if I declare all the variables at the start the program looks clearer to me. But if its a bad habit to get into I won't do it.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >But if its a bad habit to get into I won't do it.
    This is the territory of style where nobody is right and everything is based on preference. I prefer to use C style variable declarations because then I know where to find them regardless of the program. The one exception is loops, I find the C++ for loop very useful:
    for ( int i = 0; i < something; i++ )

    -Prelude
    My best code is written with the delete key.

  6. #6
    Linguistic Engineer... doubleanti's Avatar
    Join Date
    Aug 2001
    Location
    CA
    Posts
    2,459
    >C++ removes this requirement

    y'know that's always been a vice of myne about C++, i've always wondered why they have it that way, i mean it helps readability, but i'd suffice to say that the problems it presents [in duplicating variable declarations] outweighs it... [i try to keep a scope as small as possible anyhow per function...] and plus doesn't it just look kinda messy? i guess it's just what i'm used to... hmm.... can we give any example where it'd be necessary [if at all which i doubt] and or a better choice than declaring at the start of a block? thanks!
    hasafraggin shizigishin oppashigger...

  7. #7
    Blank
    Join Date
    Aug 2001
    Posts
    1,034
    In c++ as the constructor of a class gets called as soon
    as the variable is defined it's sometimes useful to define
    variables anywhere. I think it's usually a good idea
    to section off the part of the code where you define
    the variables even if it's not at the very beginning.

  8. #8
    Linguistic Engineer... doubleanti's Avatar
    Join Date
    Aug 2001
    Location
    CA
    Posts
    2,459
    ah i see... i forgot about that, automated constructyon...

    well tho, just for sake of understanding... shouldn't your class be as tight and independant and closed-box as possible anyhow, so that only the scope matter, not instance position within scope? thank you...
    hasafraggin shizigishin oppashigger...

  9. #9
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    Here is a code snippet of mine where I didn't put variable declaration at the top of the scope.
    Code:
    		std::string identifier = Util::getNextIdentifier(input);		
    
    		Util::makeLowercase(identifier);
    		Util::eraseSpaces(identifier);
    		// not at top.. constructor requires processing of identifier to be initalized
    		ActionMap_t::iterator i = actionMap.find(identifier);				
    		// if the identifier was added previously to the map
    		if (i != actionMap.end()) {  
    			// call the correpsonding action func to read the value from input
    		//	cout << identifier << endl;
    			#ifdef DEBUG_PARSE_PARSER
    				debugOut << "\tcalling getValue() for identifier \"" << identifier << "\"" << endl;
    			#endif
    			i->second->getValue(input);
    		} else {
    			if (!input.eof()) {
    				input >> junk;
    			/*	std::cout << identifier << " not recognized, corresponding junk data "
    					<< junk << endl;
    			*/
    			}
    		}
    While I could have gave i a smaller scope (starting brackets just before it's declaration), it wouldn't have changed the effect of the code at all ,objects would still be destroyed at the same time, the only change would be that the code below the declaration would be indented more.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

  10. #10
    Registered User
    Join Date
    Jan 2002
    Posts
    381
    >>hmm.... can we give any example where it'd be necessary [if at all which i doubt] and or a better choice than declaring at the start of a block? thanks!

    Some times in big switch statments (eg anything to do with windows) it actually looks neater to put them inside the switch statment. Although even then I still put them just after the case. eg:
    Code:
        case WM_INITDIALOG : const char* CircName;
                             HWND EditHandle; 
                             CircName = crMain.Name.c_str();
    
                             SetDlgItemText(hwndDlg,
                                            IDC_CCN_NAME,
                                            CircName);
                             EditHandle = GetDlgItem(hwndDlg,
                                                     IDC_CCN_NAME);
                             SetFocus(EditHandle);
                             SendMessage(EditHandle,
                                         EM_SETSEL,
                                         0,-1);
                             return 0;
                             break;
    If you own a piece of land and there is an volcano on it and it ruins a
    nearby town, do you have to pay for the property damage?

  11. #11
    Linguistic Engineer... doubleanti's Avatar
    Join Date
    Aug 2001
    Location
    CA
    Posts
    2,459
    oh thats a good one... [sometimes i might even put braces around the case segment of a switch, especially if it's a larger scope]
    hasafraggin shizigishin oppashigger...

  12. #12
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,831
    >>>
    I prefer to use C style variable declarations because then I know where to find them regardless of the program.
    <<<

    I'm with Prelude on this one, (actually I also declare my loop counters at the top as well). Our house coding standard also requires this, as did the last house I was at.

    Because something is possible does not make it desirable!
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  13. #13
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    >>>
    I prefer to use C style variable declarations because then I know where to find them regardless of the program.
    <<<

    Yep. Variables at the top of the function. If you need to call the constructor somewhere else, use a pointer and 'new'. But declare the pointer at the top.
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  14. #14
    Linguistic Engineer... doubleanti's Avatar
    Join Date
    Aug 2001
    Location
    CA
    Posts
    2,459
    >Yep. Variables at the top of the function. If you need to call the constructor somewhere else, use a pointer and 'new'. But declare the pointer at the top.

    I agree too. Hmm... and I guess I'm suprised that you go out of your to declare it at the top, even like this, just so you can get your constructor called at the right point in your program. I've never had to call a constructor at a specific time other than at the very beginning of the scope of a function [usually the main () as well, by the way] And I usually program constructors so that they don't need to be called any time except before the class instance is used [which goes anyhow since it's, after all, a constructor]. Same with destructors. Can you think of an example where a constructor [of a class relatively independant of other data, so no global data mingling], would have to be called in a specific point other than at the beginning of a scope? Thank you.
    hasafraggin shizigishin oppashigger...

  15. #15
    Registered User
    Join Date
    Jan 2002
    Location
    Vancouver
    Posts
    2,220
    Originally posted by shtarker
    Where in the nursery rhyme does it say humpty dumpty is an egg?
    Good god, I was thinking the same thing myself a few days ago.

    and how do they expect horses to perform major reconstructive surgery?

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Is it bad style of coding ??
    By noobcpp in forum C++ Programming
    Replies: 15
    Last Post: 11-06-2008, 09:39 AM
  2. Your Coding Style?
    By Krak in forum A Brief History of Cprogramming.com
    Replies: 45
    Last Post: 06-02-2005, 08:19 AM
  3. Coding style?
    By Brian in forum A Brief History of Cprogramming.com
    Replies: 43
    Last Post: 10-22-2003, 11:26 AM
  4. Tab Controls - API
    By -KEN- in forum Windows Programming
    Replies: 7
    Last Post: 06-02-2002, 09:44 AM
  5. coding style
    By ActionMan in forum Linux Programming
    Replies: 1
    Last Post: 10-03-2001, 07:36 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21