CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 31
  1. #1
    Join Date
    Jun 2009
    Posts
    65

    Red face Reinitializing variables & their speed sacrifice

    My C++ teacher states that one should not initialize a variable at declaration time (yes i know who made her a teacher!?). Although I'm past the C# point, & VCL, & GDI in C/C++, I find this amusing & irritating at the same time.

    so for the foll. code:

    Code:
    //It's C Code, so cant initialize 'a' inside loop.
    int main()
    {
    	int a=0,b=0;
    	scanf(...,&b)
    	for(a=0;a<10;a++)
    		...	
    return 1;
    }
    She says:
    1. Why the hell use int main() when void main() works fine. Let's just not get started on her ignorance to good coding practices & her ignorance to OS's error handling. I just skip it thinking she's ignorant.

    2. Why initialize b. When b is inputted. ***?
    3. Why initialize a, when you reinitialize it in loop. *** x2?

    OK, as we all know it's ALWAYS a good practice to ZeroMemory() or atleast initialize a variable to 0 or NULL. Her only case may appear a bit(0.001&#37 effective, if this practice poses a speed loss?

    Only if assigning a=0 inside loop or declaring b=0 at initialization poses speed loss, then only her arguments might be only a bit(0.001%) effective, otherwise I'll declare war.

    Can anyone tell if these practices do really pose a speed issue?

    Thanks,
    Nisheeth
    Last edited by nbaztec; March 9th, 2010 at 01:59 PM.

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Reinitializing variables & their speed sacrifice

    void main isn't legal C++. Some compilers let you get away with it, but it isn't legal.

    Your teacher is right that initializing isn't always necessary, but if you get in the habit, you're less likely to forget to do it when it is necessary.

    2 and 3, good question. She's right that it adds nothing.

    Better question, why even declare a outside the loop. The only reason for that is if you need the scope to persist outside the loop. Sometimes you may, but not usually.

    Back in the old days, programmers really did have to try really hard to optimize their code. The first system I worked on had 4 MB, that's megabytes of memory and 120 concurrent users. It was imperative to write small, tight, efficient code. These days it's still important, but you don't have to worry about the minutia the way we used to.
    Last edited by GCDEF; March 9th, 2010 at 09:34 AM.

  3. #3
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by nbaztec
    //It's C Code, so cant initialize 'a' inside loop.
    Incidentally, if you can use // to denote a comment, then it is C99 code, thus you can declare and initialise a in the init statement of the for loop
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  4. #4
    Join Date
    Jun 2009
    Posts
    65

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by GCDEF View Post
    void main isn't legal C++. Some compilers let you get away with it, but it isn't legal.
    Yes, I know this that's why I don't mind if she insists upon using void main(), coz I know I'm danm right in using int main().

    Your teacher is right that initializing isn't always necessary, but if you get in the habit, you're less likely to forget to do it when it is necessary.

    2 and 3, good question. She's right that it adds nothing.
    But isn't it that suppose I later on added another loop before the first one('a') or design a function (for 'b') it may pose some risk( I know I'll be the one responsible, but building a safe code is always good).
    The same variables I use in many places, as we all know in programming Memory is everything. I mainly focus on reducing memory usage, avoiding time loss due to redundant looping & using Multi-threading(I know this doesn't fit here, but in VC++ I do it). And, I may be wrong, but isn't it always recommended to either ZeroMemory() or assign Null to variables. Even Default constructors do it. And we know that a default constructor is called anyway. So does it matter much is we assign values explicitly?

    Even in C++ using try(), catch() throw may pose some speed losses but they make the code a lot more efficient, isnt it?

    Better question, why even declare a outside the loop. The only reason for that is if you need the scope to persist outside the loop. Sometimes you may, but not usually.
    same for @laserlight
    Dunno why but we use TC++, a clearly good but outdated compiler, that's prone to make memory leaks. I learnt it the hard way. The C file created lets you use the '//' Comments but the variables have to be defined at the start only, strange, but it throws error.

    Back in the old days, programmers really did have to try really hard to optimize their code. The first system I worked on had 4 MB, that's megabytes of memory and 120 concurrent users. It was imperative to write small, tight, efficient code. These days it's still important, but you don't have to worry about the minutia the way we used to.
    By that I guess your a veteran programmer, and many times better than me. My respects. Thanks for replying. Highly Appreciate it.

  5. #5
    Join Date
    Jul 2002
    Location
    Portsmouth. United Kingdom
    Posts
    2,727

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by GCDEF View Post
    Back in the old days, programmers really did have to try really hard to optimize their code. The first system I worked on had 4 MB,
    Is this going to be the start of a thread where all the oldies start bragging about how 'you had it easy mate' as they used to write applications by entering the instructions in binary via switches on the front panel

    BTW You had it easy mate! I first started to program on a PDP11/04 with memory measured in a few kilobytes...
    "It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
    Richard P. Feynman

  6. #6
    Join Date
    Jun 2009
    Posts
    65

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by JohnW@Wessex View Post
    Is this going to be the start of a thread where all the oldies start bragging about how 'you had it easy mate'
    BTW You had it easy mate!
    lol...but a firm no. Well the times at which u guys programmed sure were....um...tight!

  7. #7
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by nbaztec
    Yes, I know this that's why I don't mind she insists upon using void main(), coz I know I'm **** right in using int main().
    As long as you know what is correct, then it does not really matter in an academic environment like yours. That said, you could show her the answer to this FAQ on Can I write "void main()"?, and casually point out that its author, Bjarne Stroustrup, College of Engineering Chair Professor in Computer Science at Texas A&M University, is the designer and original implementer of C++.

    Quote Originally Posted by nbaztec
    And, I may be wrong, but isn't it always recommended to either ZeroMemory() or assign Null to variables.
    Taken literally, no. Zero initialisation is not always the most sensible thing to do, and in fact if you can follow the rule of declaring variables near first use, defaulting to zero initialisation should actually be an exception rather than the norm.

    Quote Originally Posted by nbaztec
    Even Default constructors do it. And we know that a default constructor is called anyway.
    Whether a default constructor performs zero initialisation depends on its semantics and implementation.

    Quote Originally Posted by nbaztec
    So does it matter much is we assign values explicitly?
    In the case where a variable will be immediately assigned to, initialisation for the sake of initialisation might confuse a reader - or it might not - thus it becomes a matter of style. But this is only if it is coupled with the rule that variables should be declared near first use, otherwise the initialisation becomes initialisation for the sake of defensive programming.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  8. #8
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by nbaztec View Post
    The same variables I use in many places, as we all know in programming Memory is everything. I mainly focus on reducing memory usage, avoiding time loss due to redundant looping & using Multi-threading(I know this doesn't fit here, but in VC++ I do it). And, I may be wrong, but isn't it always recommended to either ZeroMemory() or assign Null to variables. Even Default constructors do it. And we know that a default constructor is called anyway. So does it matter much is we assign values explicitly?
    I just bought a PC with 6GB of RAM for $409. RAM is cheap. You want to be careful, but if you're reusing variables rather than allocating a few extra ints, you're not programming well.

    Default constructors don't initialize memory, and while it won't hurt to do it, there's nothing gained by initializing something to a value that you turn around and overwrite right away. As I said before, it's just a safe habit to develop so that you don't forget to do it when you need to.

  9. #9
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by nbaztec View Post
    She says:
    1. Why the hell use int main() when void main() works fine.
    It does?
    Code:
    void main()
    {
    }
    Code:
    Thank you for testing your code with Comeau C/C++!
    Tell others about http://www.comeaucomputing.com/tryitout ! 
    
    Your Comeau C/C++ test results are as follows: 
    
    
    Comeau C/C++ 4.3.10.1 (Oct  6 2008 11:28:09) for ONLINE_EVALUATION_BETA2
    Copyright 1988-2008 Comeau Computing.  All rights reserved.
    MODE:strict errors C++ C++0x_extensions
    
    "ComeauTest.c", line 1: error: return type of function "main" must be "int"
    	So use int main() OR int main(int argc, char *argv[])
      void main()
           ^
    
    1 error detected in the compilation of "ComeauTest.c".
    
    In strict mode, with -tused, Compile failed
    Also, technically, it need not work fine.

    There are some older compilers out there that will produce code that will fail if the wrong return type for main() is used (unfortunately, these compilers do not check if you have the wrong return type for main). The reason for this is that you, the programmer, is indicating to the compiler one thing (that main doesn't return anything), but in reality, main() does return something. So code is generated that implies that a return is not done, but a return is done.

    So what do you have? You have a program that either produces undefined behaviour on exit, or some other issue -- usually return/stack related issues.

    The correct return type for main() is int. There is no ambiguity about it.

    Here is an older 'C' link:

    http://users.aber.ac.uk/auj/voidmain.shtml

    Regards,

    Paul McKenzie

  10. #10
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by Paul McKenzie
    The correct return type for main() is int. There is no ambiguity about it.

    Here is an older 'C' link:

    http://users.aber.ac.uk/auj/voidmain.shtml
    The situation for C is slightly different as C99 permits the main function (in a hosted environment) to have a return type other than int if the implementation allows for it, thus nbaztec's teacher could use this combined with the compiler's documentation as a defense, albeit a poor defense that is rather unbecoming of a teacher. (Why mandate something compiler specific when something standard is available with no disadvantage?) But the class is apparently using C++, so this point is moot as the compiler itself is non-conforming in this respect.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  11. #11
    Join Date
    Jun 2009
    Posts
    65

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by GCDEF View Post
    I just bought a PC with 6GB of RAM for $409. RAM is cheap.
    Wish I could have 1 too..
    Quote Originally Posted by GCDEF View Post

    You want to be careful, but if you're reusing variables rather than allocating a few extra ints, you're not programming well.
    I only use variables which I am **** sure wont be used again, as in a case switch nearing program termination. But if a problem can be done without the need of additional 2 bytes, its always better. For small problems this can be rightfully achieved. Though I personally declare separate variables in my day-to-day projects which span thousands of lines, just for the sake of better understandability of various variables.

    Default constructors don't initialize memory,
    Yes, I know, but they do initialize. so maybe i "guess" int

    As I said before, it's just a safe habit to develop so that you don't forget to do it when you need to.
    Whenever something can be done in two ways, someone will be confused. Whenever something is a matter of taste, discussions can drag on forever. Stick to one pointer per declaration and always initialize variables and the source of confusion disappears.
    -Bjarne Stroustrup's Comment

  12. #12
    Join Date
    Jun 2009
    Posts
    65

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by laserlight View Post
    The situation for C is slightly different as C99 permits the main function (in a hosted environment) to have a return type other than int if the implementation allows for it, thus nbaztec's teacher could use this combined with the compiler's documentation as a defense, albeit a poor defense that is rather unbecoming of a teacher. (Why mandate something compiler specific when something standard is available with no disadvantage?) But the class is apparently using C++, so this point is moot as the compiler itself is non-conforming in this respect.
    Really, does C99(does C89?) really permit other datatypes, I mean, I cant imagine the blasphemy it will bring upon the OS if my Windows/LinuX detects 'A'/2.3657 coming as a return type -_-"

    And ya the compiler(TC++ -classic, I personally hate it.) is somewhere b/w C & C++, and at the same time neither both, it reports some errors of C & some of inherited C++.

    P.S. void main() is like a manifested pestilence & ignorance is the one breeding it. I laugh when people say void main() is better coz u dont have to return anything. The best part, they dont even know where that return value goes...Will love to see their PCs crashing 1 day, just because of a stack overflow/pop arising outta void main().
    Last edited by nbaztec; March 9th, 2010 at 12:17 PM.

  13. #13
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by nbaztec View Post
    Wish I could have 1 too..

    But if a problem can be done without the need of additional 2 bytes, its always better.
    No it's not. Ease of maintenance and readability is way, way, way more important than saving two bytes. Variables should be named to give an indication of what they do and how they're used. If somebody that worked for me named variables a, b and c, they'd be rewriting their code or looking for new work. Code has to be easy to understand.

  14. #14
    Join Date
    Jun 2009
    Posts
    65

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by laserlight View Post
    In the case where a variable will be immediately assigned to, initialisation for the sake of initialisation might confuse a reader - or it might not - thus it becomes a matter of style. But this is only if it is coupled with the rule that variables should be declared near first use, otherwise the initialisation becomes initialisation for the sake of defensive programming.
    Agreed it's a Defensive Programming, but so are try, catch, throw. But I know you too might have used various GDI functions for Windows Identifiers, Pids, Process Identifiers....and I many a times got erratic results, just because I didnt ZeroMemory() or NULL them.

  15. #15
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: Reinitializing variables & their speed sacrifice

    Quote Originally Posted by nbaztec
    Really, does C99(does C89?) really permit other datatypes
    I believe C89 does as well, but I do not feel like checking for something that has little practical use when just using int as the return type will always work on a conforming implementation.

    Quote Originally Posted by nbaztec
    I mean, I cant imagine the blasphemy it will bring upon the OS if my Windows/LinuX detects 'A'/2.3657 coming as a return type -_-"
    I guess that it is the implementation's job to translate whatever value you return with the return types that it allows to something that makes sense to the host environment.

    Quote Originally Posted by GCDEF
    No it's not. Ease of maintenance and readability is way, way, way more important than saving two bytes. Variables should be named to give an indication of what they do and how they're used. If somebody that worked for me named variables a, b and c, they'd be rewriting their code or looking for new work. Code has to be easy to understand.
    Furthermore, data flow analysis might result in the compiler optimising such that the two byte penalty is only imaginary.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Page 1 of 3 123 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured