Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

"It's far more readable and — as a bonus — compiler is likely to produce more efficient code."

I want to learn more about this, when or how do you know a compiler produced efficient code? Does anybody have any interesting links for reads on this?



You profile the generated code, be that in terms of execution speed or size in bytes: If it's better then it's better.

In this case C++ exceptions are practically zero cost so I don't quite believe that the compiler will generate more efficient code unless it elides some of the C version based on context (Otherwise the if statements aren't free)


Well, I think most people do it by some sort of "trial and error", the tool of choise is Matt Godbolt's Compiler Explorer [1]

I sometimes listen to the CppCast Podcast and one of the Hosts, Jason Turner, likes to write code in modern C++ for some vintage computers. He tests code bits in Compiler Explorer for that. He also has a YouTube Channel where he does that [2]

[1] https://gcc.godbolt.org/

[2] https://www.youtube.com/user/lefticus1


The example

    int rc = fx ();
    if (rc != 0)
        handle_error ();
can be simply converted into ASM

    ; call fx() and copy to acc
    JNZ handle_error
    ; rest of code
    handle_error: 
      ; code of handle_error()
whereas exceptions in C++ need to generate a lot more code than this


The C++ code can be compiled in such a way that it has no branching e.g. stack unwinding instead, which is slower in the case of an exception being thrown - However, exceptions shouldn't be used for non-exceptional circumstances.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: