Thread: General questions about style, syntax and best practices.

  1. #16
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    No, the lesson is, "Use exceptions for errors that are forced on you by the environment." Files that have gone missing, network connections that are broken, memory that has run out.
    When your application consists of smaller components, one component could treat all other components as "environment" which would extend this notion beyond things that are really outside the program, but the general idea is still there.
    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

  2. #17
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    So, what I gathered from this thread: "Avoid exceptions unless the problem is 'somewhat' irrecoverable".
    O_o

    That's a little extreme while being vague.

    I can't presently think of a way to put it in words.

    I would not phrase it the way CornedBee has either, but as he said, the general idea is there. ^_^;

    Soma
    Last edited by phantomotap; 07-08-2012 at 02:06 PM. Reason: *derp*

  3. #18
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    I tend to use exceptions for situations that should not happen. How you define "should" varies, of course, but it could mean that most executions of the program will never fire that exception, or it could mean that there's no good way to recover, etc. Basically, it's something very unusual. It's worth keeping in mind that exceptions are expensive in terms of execution speed, so you really don't want an exception firing every time the player tries to unsuccessfully fire a weapon.

    asserts are for programmer errors that shouldn't happen. Exceptions are a similar mechanism for runtime errors, the way I see it.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #19
    Registered User
    Join Date
    Jul 2012
    Posts
    23
    I apologize for resurrecting this thread, but I figured it'd be better writting here than making a new one.

    I have a few more questions:

    1- Sould non void functions always return a value ?
    Lets say I have a function that returns true if some condition is met. Should it return false if it isn't ?

    2- does checking many conditions at once affects performance more than using nested if-elses ?
    e.g:
    Code:
    if(someConditionIsMet) && (someConditionIsMet) &&(someConditionIsMet)
        doSomething();
    
    VS
    
    if (someConditionIsMet)
        if(someConditionIsMet)
            if (someConditionIsMet)
                doSomething();
    3- is it OK to allow a variable to be assigned the same value over and over, for convenience purposes. Or is it better to check if the variable has the value already ?
    e.g:
    Code:
    ...
    intVar = 7;
    ...
    VS
    ...
    if (intVar != 7)
        intVar = 7;
    ...
    4- Which leads to the main question, what is more expensive for the cpu; retrieve the contents on a var and compare them, or simply writte to to memory ?

    Thanks in advance.

  5. #20
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by skyliner
    1- Sould non void functions always return a value ?
    Lets say I have a function that returns true if some condition is met. Should it return false if it isn't ?
    Yes.

    Quote Originally Posted by skyliner
    2- does checking many conditions at once affects performance more than using nested if-elses ?
    It depends on what the compiler does, and in fact the result could be exactly the same. So, strive for readable code.

    Quote Originally Posted by skyliner
    3- is it OK to allow a variable to be assigned the same value over and over, for convenience purposes. Or is it better to check if the variable has the value already ?
    It depends on how expensive it is to copy the value versus how expensive it is to check the value, with other factors that may come into play, plus what the compiler does.

    Quote Originally Posted by skyliner
    4- Which leads to the main question, what is more expensive for the cpu; retrieve the contents on a var and compare them, or simply writte to to memory ?
    It depends. If there is a performance bottle neck related to this, I would test and measure rather than try and reason about it, though I might reason about it when analysing the results.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #21
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    Quote Originally Posted by laserlight View Post
    It depends on what the compiler does, and in fact the result could be exactly the same. So, strive for readable code.
    Would many if's in a row utilize short circuiting like the conditional operators ?

  7. #22
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by manasij7479
    Would many if's in a row utilize short circuiting like the conditional operators ?
    Logically,
    Code:
    if (a && b) {
        // ...
    }
    is equivalent to:
    Code:
    if (a) {
        if (b) {
            // ...
        }
    }
    The short circuiting is implied in the logical structure.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #23
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Quote Originally Posted by skyliner View Post
    4- Which leads to the main question, what is more expensive for the cpu; retrieve the contents on a var and compare them, or simply writte to to memory ?
    It's unlikely to matter very much, especially if optimizations are enabled. The compiler will likely reason that
    Code:
    var = 7;
    and
    Code:
    if(var != 7) var = 7;
    are exactly equivalent. In fact I'd be inclined to give it the first and simpler version, just so that the compiler's internal data structures are simpler (thus giving it a better chance of being able to perform more complex, and ultimately more useful, compiler optimizations).

    Let me explain in a bit more detail what's going on in each case. The compiler will place variables in registers (especially in the context of a loop), so that "var = 7" probably won't immediately put a request to set var onto the system bus. It will just set a register. When the function exits or whatever, the register value will be put back into memory. But while var is in a register, it involves almost no cost to check it against 7; it will literally be one instruction cycle (well, maybe a few more but certainly very few).

    When the value is put on the system bus, however, that's when things slow down. (This is why you should enable compiler optimizations.) It will probably take at least a hundred CPU cycles for the value to be written to memory, maybe less if it happens to be able to fit into the L1 cache. See, main memory access (RAM) is so slow that computers have an L1 cache, a larger but slower L2 cache, and sometimes even an L3 cache to speed it up. This is why the compiler will put your variables into registers.

    I'm not certain, but an educated guess would be that a write-only instruction would be faster than "if(var != 7) var = 7"; your program wouldn't have to read var into memory, just put a write on the bus. So that's another reason in favour of "var = 7".

    Finally, modern CPUs almost always execute several instructions simultaneously (in parallel, in the "pipeline"). If your program has 100 instructions a CPU will start with the first 8 at least, execute different stages of each instruction, shuffling them around so that there aren't any dependencies. If the CPU can't do this, it stalls -- it waits, idle, doing nothing. You could have a pipeline stall if you have lots of memory accesses (but for certain programs, you can't avoid this). You could also have a pipeline stall if a branch-prediction went wrong. Because the CPU has to guess which way a branch (e.g. for an if statement) will go: to take the branch, or not to take it? And if it guesses wrong it has to flush all those partially-executed instructions it was evaluating and start over. Pretty bad for performance.

    The upshot? I think "if(var != 7) var = 7" will introduce a branch in unoptimized machine code. And any branch like that has the potential to be incorrectly guessed and cause a pipeline stall. Basically, don't introduce branches if you don't have to. But again, if you have optimizations enabled the compiler will almost certainly do away with the branch.

    I should mention that these are very low-level details that won't matter one whit unless your code is inside a whole bunch of loops that execute millions or billions of times. An average unoptimized function call has way more impact (plus memory accesses!) than you introducing a branch ever would. And if it's optimized, chances are the compiler will rewrite it so much that you wouldn't recognize your own code, if you ever looked at its assembly.

    So basically, don't worry about it unless you've really determined that something is a bottleneck with some kind of profiler. Write whatever code makes the most sense, in the context of your program; readability is what matters. If it's slow, turn up the optimization level and let the compiler do what compilers do best: magic.

    [The "magic" numbers in this post are meant as rough approximations only. Take them with a grain of salt, but the overall idea holds.]
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  9. #24
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Quote Originally Posted by dwks View Post
    The compiler will likely reason that
    Code:
    var = 7;
    and
    Code:
    if(var != 7) var = 7;
    are exactly equivalent.
    They aren't under the C++11 memory model, and a compiler that reasons this way is buggy. Yes, it's weird, but in theory you could construct a program that produces a race condition with the first snippet but none with the second.
    That said, the first snippet is still better unless the type of var is really far more expensive to copy than to compare.
    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

  10. #25
    Registered User
    Join Date
    Jul 2012
    Posts
    23
    Thank you all very much for your answers.
    Please, allow me to clarify that I have absolutely no problems with performance. At this point my limited skills allow me to write little more than simple console applications, which barely make my CPU yawn.

    The reason behind my question is purely academical; I'd like to build a solid base and acquire good programming habits, that's all.

    Quote Originally Posted by dwks View Post
    I should mention that these are very low-level details that won't matter one whit
    I am fascinated by those low level details. It is the reason I switched my major to engineering instead of CS and I hope someday I can master those obscure secrets

    Thanks for your explanation!


    EDIT: is there any chance you guys have any advice on how to write proper source code documentation ?
    I found this resource http://www.bgsu.edu/departments/comp...mentation.html while searching online, but I'm a bit overwhelmed by its level of detail. I think it might be overkill for my 450+ lines project.
    Is all that really necessary, specially the pseudocode section ?
    Last edited by skyliner; 07-16-2012 at 03:23 AM.

  11. #26
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by skyliner
    is there any chance you guys have any advice on how to write proper source code documentation ?
    I found this resource C++ Program Documentation Guidelines while searching online, but I'm a bit overwhelmed by its level of detail. I think it might be overkill for my 450+ lines project.
    Is all that really necessary, specially the pseudocode section ?
    Please start a new thread for this topic. If not, those people who have something to say about "how to write proper source code documentation" but nothing to say about "style, syntax and best practices" simply won't help you because they had no inkling that you were asking about it.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #27
    Registered User
    Join Date
    Jul 2012
    Posts
    23
    Quote Originally Posted by laserlight View Post
    Please start a new thread for this topic. If not, those people who have something to say about "how to write proper source code documentation" but nothing to say about "style, syntax and best practices" simply won't help you because they had no inkling that you were asking about it.
    Dully noted

    Though I really was kinda targeting a specific audience, I thought maybe one of you noble and gracious folks, that have diligently answered my questions would have a hint or two. Specially you.

    But thanks for the tip man, I'll certainly make a new thread for other alien topics in the future.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [General Help] Dynamic Arrays and General Pointer syntax
    By Amberlampz in forum C Programming
    Replies: 22
    Last Post: 07-26-2011, 10:58 PM
  2. Beginner question about understanding general Syntax
    By lucidrave in forum C++ Programming
    Replies: 15
    Last Post: 08-13-2009, 03:57 PM
  3. A Few General C Questions
    By Jedijacob in forum C Programming
    Replies: 13
    Last Post: 02-17-2005, 02:47 AM
  4. Syntax Style
    By darfader in forum C Programming
    Replies: 2
    Last Post: 10-03-2003, 05:21 AM
  5. General Dev Questions
    By drdroid in forum C++ Programming
    Replies: 1
    Last Post: 09-11-2002, 08:06 PM