Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. New code in C? Where and why, versus C++?

New code in C? Where and why, versus C++?

Scheduled Pinned Locked Moved The Lounge
c++questiondata-structuresooptutorial
58 Posts 24 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Stuart Dootson

    All the code for it is contained in [a single C++ header file](https://github.com/SuperV1234/vittorioromeo.info/blob/master/extra/passing\_functions\_to\_functions/function\_view.hpp) - you could just incorporate that into your build :-)

    Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

    H Offline
    H Offline
    honey the codewitch
    wrote on last edited by
    #49

    decltype(auto) operator()(TArgs... xs) const

    Doesn't seem to matter how much time I spend looking at C++ code, I'm still always learning new things about it. Didn't know decltype(auto) was a thing. That's pure magic. Now I know how they do their elastic functors. :-D

    Real programmers use butterflies

    S 1 Reply Last reply
    0
    • H honey the codewitch

      decltype(auto) operator()(TArgs... xs) const

      Doesn't seem to matter how much time I spend looking at C++ code, I'm still always learning new things about it. Didn't know decltype(auto) was a thing. That's pure magic. Now I know how they do their elastic functors. :-D

      Real programmers use butterflies

      S Offline
      S Offline
      Stuart Dootson
      wrote on last edited by
      #50

      There's more than one way to skin that cat :-) `decltype(auto)` is used instead of `auto` here because `auto` strips references from the type of the thing it's inferring from (e.g. if your function returned a `std::string const&`, using `auto` would cause it to return by value, whereas `decltype(auto)` would cause it to return the reference). However, in this case, `auto&&` has the same semantics as `decltype(auto)`, and will return by reference if that's what's wanted. `auto` return types are useful for places where the return type is difficult (or impossible) to state statically - consider this code (which is valid c++17), which returns a string if it's instantiated for `std::string` and an integer otherwise... There are situations where something like this is useful. ```c++ template auto foo(T const& t) { if constexpr (std::is_same_v) { return "Hello"; } else { return 3; } } int main() { std::cout << foo(12) << std::endl; std::cout << foo(std::string("a")) << std::endl; } ``` outputs 3 Hello

      Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

      H 1 Reply Last reply
      0
      • S Stuart Dootson

        There's more than one way to skin that cat :-) `decltype(auto)` is used instead of `auto` here because `auto` strips references from the type of the thing it's inferring from (e.g. if your function returned a `std::string const&`, using `auto` would cause it to return by value, whereas `decltype(auto)` would cause it to return the reference). However, in this case, `auto&&` has the same semantics as `decltype(auto)`, and will return by reference if that's what's wanted. `auto` return types are useful for places where the return type is difficult (or impossible) to state statically - consider this code (which is valid c++17), which returns a string if it's instantiated for `std::string` and an integer otherwise... There are situations where something like this is useful. ```c++ template auto foo(T const& t) { if constexpr (std::is_same_v) { return "Hello"; } else { return 3; } } int main() { std::cout << foo(12) << std::endl; std::cout << foo(std::string("a")) << std::endl; } ``` outputs 3 Hello

        Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

        H Offline
        H Offline
        honey the codewitch
        wrote on last edited by
        #51

        I had no idea you could declare auto as a return value in some cases. I've only recently taken to using lambdas in C++ so that's probably part of it. I spent a long time away from C++ and am still catching up with C++ standards. So much has changed.

        Real programmers use butterflies

        1 Reply Last reply
        0
        • D David ONeil

          I was being facetious, because in C I believe you are often forced to cast where you don't in C++. IE, from one of my articles...

          SwcTabCtrl* tabControl = (SwcTabCtrl*) tabsC[selectedTabC];

          in C, whereas C++ is:

          SwcTabCtrl * tabControl = tabsC[selectedTabC];

          I don't remember the reason for the forcing of the cast, but I believe it is some C-ism. Anyway, I detest the first code with great detestation. You shouldn't, though, because you are a witch!

          The Science of King David's Court | Object Oriented Programming with C++

          W Offline
          W Offline
          W Balboos GHB
          wrote on last edited by
          #52

          This has been more-or-less a peeve of mine between C++ and C#, but when it comes to casting, or for that matter, having to use (and know the difference between!) '->' '::' and '.', if find the effective dumbing down of C# unfortunate. So - if forced to cast, perhaps it's a way to keep all the ducks in order and also letting you know there are ducks. Behind the scenes "promotions" make life easier (and in certain SQL I depend upon them) but understanding being built into the code is (in my opinion) a plus.

          Ravings en masse^

          "The difference between genius and stupidity is that genius has its limits." - Albert Einstein

          "If you are searching for perfection in others, then you seek disappointment. If you seek perfection in yourself, then you will find failure." - Balboos HaGadol Mar 2010

          1 Reply Last reply
          0
          • H honey the codewitch

            This is something I'm really curious about, and maybe it's just because I'm newish to coding small gadgets, though most of it is comfortable to me since I cut my teeth on 6502 CPUs back in the day. What is the purpose of writing new code in C for targeting, well ... anything? I've put away my C compiler and simply relied on limited use of C++ features to keep the footprint the same as it is in C: 1. no vtables. slightly complicates inheritance, as you can no longer do virtual ~foo() {} 2. extremely limited use of the STL, if at all. I typically use std::atomic if available, but not std::string, for example 3. judicious use of extern "C" when exporting my main, or importing "C" headers 4. no exceptions/SEH/etc, RTTI or other C++ frills that bloat code or stack Why do I do it? Primarily for that sweet sweet RAII, but also general source management. Classes can keep everything together. HPP based libraries are useful for simplifying distribution. public and private members replace the need for hiding in C files in many cases. and many other reasons. Should I not be doing it? Is there a reason this is bad form? Is there a reason you wouldn't?

            Real programmers use butterflies

            G Offline
            G Offline
            Gary R Wheeler
            wrote on last edited by
            #53

            I think the reason many embedded programmers prefer C to C++ lies in simplicity. If they are programming in C, they don't have to keep in mind nearly as many of the implications of how they are writing their code. It's an example of WYSIWYG. C++ provides far too many mechanisms like inheritance and overloading that impact performance and memory usage. There's also a certain inertia in the embedded software industry. I remember when C was viewed with skepticism, while it is now a mainstay. It will take a significant number of C++ adepts moving into embedded programming before the language becomes significant. It will also need for some members of the C community to leave. People like Linus Torvalds, who makes blanket statements about defects in C++ as a language that are inherent in his mono-focus on the Linux kernel.

            Software Zen: delete this;

            1 Reply Last reply
            0
            • S steveb

              Typical C++ baggage is a lots of behind the scenes function calls (ctor, copy ctor,dtor,=, &adressof. So if your program must execute in a certain amount of CPU clocks then C++ is a bad choice. Such as, you do not want to slow down "fly by wire" flap extender module by unnecessary function jumps for example

              M Offline
              M Offline
              Matt McGuire
              wrote on last edited by
              #54

              I agree with you, especially in the embedded and low level stuff, every clock tick counts. With C++ a person could use abstraction and polymorphism too much and seriously hobble a quick process. I would also add C is geared towards being closer to the metal and C++ more towards large applications, not that you can't do either in both. just use the right tool for the right job. personally I prefer the simplicity of the C language, there is a reason why it still is so popular on the TIOBE index

              1 Reply Last reply
              0
              • H honey the codewitch

                This is something I'm really curious about, and maybe it's just because I'm newish to coding small gadgets, though most of it is comfortable to me since I cut my teeth on 6502 CPUs back in the day. What is the purpose of writing new code in C for targeting, well ... anything? I've put away my C compiler and simply relied on limited use of C++ features to keep the footprint the same as it is in C: 1. no vtables. slightly complicates inheritance, as you can no longer do virtual ~foo() {} 2. extremely limited use of the STL, if at all. I typically use std::atomic if available, but not std::string, for example 3. judicious use of extern "C" when exporting my main, or importing "C" headers 4. no exceptions/SEH/etc, RTTI or other C++ frills that bloat code or stack Why do I do it? Primarily for that sweet sweet RAII, but also general source management. Classes can keep everything together. HPP based libraries are useful for simplifying distribution. public and private members replace the need for hiding in C files in many cases. and many other reasons. Should I not be doing it? Is there a reason this is bad form? Is there a reason you wouldn't?

                Real programmers use butterflies

                M Offline
                M Offline
                mischasan
                wrote on last edited by
                #55

                I use C heavily, because it's easier to write cross-platform, cross-compiler code. In particular, the ABI doesn't change between different (minor!) versions of the compiler. For performance, C tends to be *simpler* code for sharp new algorithms. That's particularly true for data-oriented designs and flow-based programming. Also for libraries that other (C++) systems depend on. There are C conventions that make "subclassing" easier. FWIW C99 made that simpler. Opinion: I'm tired of C++ trying to fix last version's problems with yet another complicated construct, (auto_ptr? smart_ptr? unique_ptr? ...) requiring code restructuring in ways that other teams may have problems grokking. C++ seems to prefer hiding things, or at least slapping another coat of paint on them. Like getting from point A to point B via a Hilbert curve.

                H 1 Reply Last reply
                0
                • M mischasan

                  I use C heavily, because it's easier to write cross-platform, cross-compiler code. In particular, the ABI doesn't change between different (minor!) versions of the compiler. For performance, C tends to be *simpler* code for sharp new algorithms. That's particularly true for data-oriented designs and flow-based programming. Also for libraries that other (C++) systems depend on. There are C conventions that make "subclassing" easier. FWIW C99 made that simpler. Opinion: I'm tired of C++ trying to fix last version's problems with yet another complicated construct, (auto_ptr? smart_ptr? unique_ptr? ...) requiring code restructuring in ways that other teams may have problems grokking. C++ seems to prefer hiding things, or at least slapping another coat of paint on them. Like getting from point A to point B via a Hilbert curve.

                  H Offline
                  H Offline
                  honey the codewitch
                  wrote on last edited by
                  #56

                  I do share your frustration with C++'s very much designed-by-committee** runtimes ** not that other languages aren't driven by standards bodies, but C++ very much "feels" like it is. Plowing through the STL standards is like trying to do pretty much anything at the DMV (at least in the states) I can't find anything to argue about with your post in fact. :thumbsup:

                  Real programmers use butterflies

                  1 Reply Last reply
                  0
                  • D Dave B 68

                    honey the codewitch wrote:

                    So if anything it seems a matter of education? Knowing what C++ will generate and what it won't.

                    Perhaps this is the biggest issue. The level of knowledge one has to earn to know how to make the compiler generate what they want and even more importantly, know what the compiler will generate when reading someone else's code. This knowledge has a cost (potentially a high cost) that needs to be maintained by the organization through the expense of time and paid experience of every developer reading or maintaining the code. That expense must be offset by the reduction in cost of using C++ features that eliminate writing boilerplate code and organizing code. I suspect with the far simpler rules/capabilities of C code, you have to look at a lot less code you didn't write to understand exactly what it is doing without resorting to using a debugger or looking at assembly. My current opinion is that the decision of C versus C++ would come down to the project size and the pool and expense of developers you want maintaining the code. Imagine a "C++ developer" jumping into a project that required diagnosing a set of code that used partial and full template specialization a few levels deep and being asked to refactor it. Could they do it? The statements "I know C++" and "I know C" carry two different levels of trust. I would trust most people who claim to know C and I can easily test their knowledge. With C++, the question for me becomes, what parts of C++ do you know and how well do you know each?

                    Dave B

                    T Offline
                    T Offline
                    TheGreatAndPowerfulOz
                    wrote on last edited by
                    #57

                    Yeah, I've seen some template stuff in C++ that seemed like voodoo to me. Just take a look at Spirit++[^] to see what I mean.

                    #SupportHeForShe Government can give you nothing but what it takes from somebody else. A government big enough to give you everything you want is big enough to take everything you've got, including your freedom.-Ezra Taft Benson You must accept 1 of 2 basic premises: Either we are alone in the universe or we are not alone. Either way, the implications are staggering!-Wernher von Braun

                    1 Reply Last reply
                    0
                    • H honey the codewitch

                      This is something I'm really curious about, and maybe it's just because I'm newish to coding small gadgets, though most of it is comfortable to me since I cut my teeth on 6502 CPUs back in the day. What is the purpose of writing new code in C for targeting, well ... anything? I've put away my C compiler and simply relied on limited use of C++ features to keep the footprint the same as it is in C: 1. no vtables. slightly complicates inheritance, as you can no longer do virtual ~foo() {} 2. extremely limited use of the STL, if at all. I typically use std::atomic if available, but not std::string, for example 3. judicious use of extern "C" when exporting my main, or importing "C" headers 4. no exceptions/SEH/etc, RTTI or other C++ frills that bloat code or stack Why do I do it? Primarily for that sweet sweet RAII, but also general source management. Classes can keep everything together. HPP based libraries are useful for simplifying distribution. public and private members replace the need for hiding in C files in many cases. and many other reasons. Should I not be doing it? Is there a reason this is bad form? Is there a reason you wouldn't?

                      Real programmers use butterflies

                      C Offline
                      C Offline
                      Chad3F
                      wrote on last edited by
                      #58

                      I can't really advise you to use one over the other (as it's your personal preference), but I can tell you that I generally avoid doing C++ code over C for my own stuff. Why? Perhaps I've been burned/annoyed by C++ too much over the decades (some of which may not be relevant anymore, but still has left a bitter taste).. [rant-begin] -- Mangling inconsistencies between compilers. -- No unified naming conventions. Camel Case vs Pascal Case vs Snake Case. -- Too much hungarian notation crap seen. -- Headers with .hpp extension vs just .h (or worse, "standard" headers with no extension, causing pointless dummy files that include the real .h file in some implementations). -- Overloading abused to non-intuitive things way too often. -- Bloated / over-complex standard libraries. -- The "new" C++ really should have been called something other than C++, since it has radically changed from early C++. -- A bunch of translating back and forth needed when dealing with C APIs (most often C strings), which adds extra overhead. -- .cpp files extensions. Always makes me think "C Pre-Processor", which predated C++. I mean, what where they thinking?! Though, .hpp files annoy me more. I use .cc when I must do C++ for my own projects. -- Wrapping everything in "new" C++ (for memory/cleanup safety). Sure, it helps, but at what cost of hidden overhead, and is still no substitute for avoiding sloppy/undisciplined coding. -- Bloated / over-complex standard libraries.. "I know that, technically, that’s only one drawback, but it was such a big one I thought I’d mention it twice." --Kryten/Red Dwarf [rant-end] In some cases I will still write a C++ wrapper for my C code, if it's a library, just for people who prefer using an OO API. Now don't get me wrong.. some of the features of C++ are nice (like function grouping, protected methods, polymorphism), but often not worth the price of all the negatives.

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups