CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 12 of 12
  1. #1
    Join Date
    Aug 2002
    Posts
    756

    How smart is the compiler?

    Hi, ALL,
    Consider the following piece of pseudo-code:

    Code:
    int Foo::Bar()
    {
        int result = 0;
        int res = <some_operation>
        if( res == <ERROR_CODE> )
        {
            // report the error
            result = 1;
        }
        if( !result )
        {
            res = <some_operation_1>
            if( res == <ERROR_CODE> )
            {
                // report the error
                result = 1;
            }
        }
    }
    This pattern will repeat n number of times, where n > 2.

    My question is: Is the compiler smart enough to do "else" instead of checking "!result" every single time?
    I'm just trying to keep my code with the decent number of spaces so that it is kept on 1 screen. Otherwise I'd add the else myself.

    I'm working with MSVC {2010 if it matters}, gcc 5.4 and clang. Using C++11.

    Thank you.

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,396

    Re: How smart is the compiler?

    Alternatively you could decrease the text size or use the monitor with the increased hight.
    Victor Nijegorodov

  3. #3
    Join Date
    Aug 2002
    Posts
    756

    Re: How smart is the compiler?

    Hi, VictorN,
    Quote Originally Posted by VictorN View Post
    Alternatively you could decrease the text size or use the monitor with the increased hight.
    I can but it will more painful to my eyes.
    And since I'm an old guy I'd like to avoid it. ;-)

    Thank you.

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: How smart is the compiler?

    You could do something like this

    Code:
    bool func1()
    {
    	int res; //<some operation 1>
    	//...
    	return res == error;
    }
    
    bool func2()
    {
    	int res; //<some operation 2>
    	//...
    	return res == error;
    }
    
    ...
    
    if (!func1() && !func2())
    	; // Functions succeeded
    else
    	; // One function failed
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  5. #5
    Join Date
    Aug 2002
    Posts
    756

    Re: How smart is the compiler?

    Hi, 2kaud,
    Quote Originally Posted by 2kaud View Post
    You could do something like this

    Code:
    bool func1()
    {
    	int res; //<some operation 1>
    	//...
    	return res == error;
    }
    
    bool func2()
    {
    	int res; //<some operation 2>
    	//...
    	return res == error;
    }
    
    ...
    
    if (!func1() && !func2())
    	; // Functions succeeded
    else
    	; // One function failed
    As I said the pattern is n times where n > 2.

    At one point I may have 25 checks and at another I can have 5.
    This is really unpredictable.

    Thank you.

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: How smart is the compiler?

    You can have the required number of functions and extend the if && statement to include as many as are required separated by &&. Also consider an array of functions where each array is the checks required for a particular event.

    Code:
    bool func1()
    {
    	int res; //<some operation 1>
    	//...
    	return res == error;
    }
    
    bool func2()
    {
    	int res; //<some operation 2>
    	//...
    	return res == error;
    }
    
    
    using myfunc = bool(*)();
    
    
    int main()
    {
    	myfunc f1[] { func1 };
    	myfunc f2[] { func1, func2 };
    
    	for (const auto& f : f1)
    		if (f())
    			break;
    //....
    	for (const auto& f : f2)
    		if (f())
    			break;
    
    }
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    Feb 2017
    Posts
    677

    Re: How smart is the compiler?

    Quote Originally Posted by OneEyeMan View Post
    I'm just trying to keep my code with the decent number of spaces so that it is kept on 1 screen. Otherwise I'd add the else myself.
    Is it just a question of pretty-printing the code? I'm using the good old K&R indentation style and in this case I would probably consider something like this,

    Code:
    int Foo::Bar() {
        int res;
        if ((res = <some_operation>) == <ERROR_CODE> ) {
            // report the error
        } else if ((res = <some_operation_1>) == <ERROR_CODE>) {
            // report the error
        } else if ((res = <some_operation_2>) == <ERROR_CODE>) {
            // report the error
        }
    }
    Last edited by wolle; August 15th, 2017 at 11:27 PM.

  8. #8
    Join Date
    Feb 2017
    Posts
    677

    Re: How smart is the compiler?

    The code in my previous post "crams" assignments and a logical expressions. This has traditionally been somewhat frowned upon and I've used it only occasionally. Now I note that in C++ 17 this style has got a face-lift and is now considered good usage. According to this (point 2):

    https://tech.io/playgrounds/2205/7-f...e/introduction

    the modern form of my code above would be:

    Code:
    int Foo::Bar() {
        if (int res = <some_operation>; res == <ERROR_CODE> ) {
            // report the error
        } else if (res = <some_operation_1>; res == <ERROR_CODE>) {
            // report the error
        } else if (res = <some_operation_2>; res == <ERROR_CODE>) {
            // report the error
        }
    }

  9. #9
    Join Date
    May 2001
    Location
    Germany
    Posts
    1,158

    Re: How smart is the compiler?

    I don't think that any of the proposed solutions are really readable.
    What about the use of exceptions? If any of the operations throw an exception in the case of an error, the calling function could elegantly cope for that:
    Code:
    int Foo::Bar() // note: return value omitted in the following
    {
        try
        {
            <some operation 1>;
            <some operation 2>;
            <...>
        }
        catch( const std::exception& ) // or whatever user-defined exception
        {
             // report the error
        }
    }

  10. #10
    Join Date
    Oct 2008
    Posts
    1,456

    Re: How smart is the compiler?

    Quote Originally Posted by Richard.J View Post
    What about the use of exceptions? If any of the operations throw an exception in the case of an error, the calling function could elegantly cope for that:
    agreed, but only if those error conditions are truly exceptional … otherwise, if the errors are part of the expected program flow you’ll incur in the cost of stack unwinding, and you’ll need to respect more stringent design constraints ( eg. don’t throw during stack unwinding, manage exception safety guarantees, manage exceptions thrown by inner code, etc… )

  11. #11
    Join Date
    Oct 2008
    Posts
    1,456

    Re: How smart is the compiler?

    Quote Originally Posted by OneEyeMan View Post
    My question is: Is the compiler smart enough to do "else" instead of checking "!result" every single time?
    such a thing is optimized both at the compiler and at the processor level; the compiler can do dead code removal ( eg. to proove that <result> doesn't change and jump ahead, use lookup table, etc... ) and/or add branch optimized instructions, the processor can also do its own branch prediction as well; so, assuming such code makes sense ( and it seems not BTW ), it's not something you should worry about performance wise, unless profiled otherwise. That said, the only way to be sure is to inspect the generated asm and/or profile the code.

  12. #12
    Join Date
    Feb 2017
    Posts
    677

    Re: How smart is the compiler?

    Quote Originally Posted by Richard.J View Post
    I don't think that any of the proposed solutions are really readable.
    What about the use of exceptions? If any of the operations throw an exception in the case of an error, the calling function could elegantly cope for that:
    Code:
    int Foo::Bar() // note: return value omitted in the following
    {
        try
        {
            <some operation 1>;
            <some operation 2>;
            <...>
        }
        catch( const std::exception& ) // or whatever user-defined exception
        {
             // report the error
        }
    }
    It's not altogether clear what the OPs requirements are but I think you have reduced the complexity a little too much. For example the OP may want to distinguish between different kinds of errors (to be able to print a relevant error message) and then you need more exceptions and perhaps additional information that most surely will complicate your solution.

    An exception statement basically is a goto control structure in disguise. Therefore, since the advent of structured programming, it is usually avoided in general code and used only for true error-handling, and I'm not at all convinced that applies here.

    I suggested an if-then chain which is a standard way to handle the OPs problem in structured programming. It should be familiar to most programmers and straightforward to read and grasp.

    Personally I'm leaning towards OO but I have waited with an example until I know whether the OP is interested. There may be some nice functional programming solution too. In any case both OO and functional will lead to less readable code for those not familiar with those paradigms. So there's no objective criterion for readability really. It's in the eye of the beholder depending on individual experience and skill.

    Anyway, I would think twice before resorting to exceptions as a general control structure. It's a slippery slope. A few changes later (possibly done by others) and the readable code you started with quite likely has turned into a complete mess of incomprehensible "spagetti". Here's a balanced view,

    http://david.tribble.com/text/goto.html
    Last edited by wolle; August 17th, 2017 at 01:50 AM.

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