Follow Slashdot stories on Twitter

 



Forgot your password?
typodupeerror
×
Programming

Someone on Medium Just Said C++ Was Better Than C (medium.com) 315

Developer David Timothy Strauss is publishing a call to code "straightforward, easy-to-reason-about approaches" -- in an essay titled "Choosing 'Some C++' Over C". (Alternate title: "C++ for Lovers of C." The problem with just picking C++ is that most criticism of it is legitimate. Whether it's the '90s-era obsession with object orientation and exceptions or the template errors that take up an entire terminal window, there have been -- and remain -- rough edges to C++. But, these rough edges are avoidable, unlike the problems in C that get worse with modern event and library programming. The opinionated essay calls for "adopting a subset of C++ to smooth out C's rough edges," arguing that C++ offer a better, type-safe approach for event-driven design (as well as destructors to avoid memory allocation leaks). Are there any readers who'd like to weigh in on the advantages of C versus C++?
This discussion has been archived. No new comments can be posted.

Someone on Medium Just Said C++ Was Better Than C

Comments Filter:
  • Indeed (Score:5, Funny)

    by hcs_$reboot ( 1536101 ) on Saturday April 01, 2017 @01:36PM (#54158047)
    "C++" > "C" (as long as > has not been overloaded..)
    • Re:Indeed (Score:5, Funny)

      by allo ( 1728082 ) on Saturday April 01, 2017 @01:54PM (#54158099)
      In fact, it is not. Try it yourself:

      #include <stdio.h>
      int main(int argc, char **argv) {
          int C=0x11;
          if(C++ > C) {
              printf("C++ is greater than C\n");
          } else {
              printf("C++ is not greater than C\n");
          }
      }

      $ ./a.out
      C++ is not greater than C
      • Re:Indeed (Score:4, Informative)

        by david.emery ( 127135 ) on Saturday April 01, 2017 @02:03PM (#54158121)

        And this highlights the difference between C and C++, and better specified/more tightly defined languages.

        Two C programmers will ask, "What will this program do?"
        Two Ada programmers will ask, "Will this program compile?" Because if it does compile, they both know (and agree on) exactly what the legal program will do.

        • What if you use Ada to write something as complex as a C interpreter ?

        • Re: Indeed (Score:5, Funny)

          by Anonymous Coward on Saturday April 01, 2017 @03:02PM (#54158317)

          Trick question. There is only one ada programmer.

        • by Kremmy ( 793693 )
          Ignorance of the definition does not negate it.
          The C statement "C++ > C" is not true because post-increment occurs after the statement has been evaluated.
        • Yet somehow, the use of ADA did not stop Ariane 501 from exploding half a minute after lift-off.

      • by Jamu ( 852752 )
        The result of "C++" > "C" is undefined because the pointers point to different objects?
        • Re:Indeed (Score:4, Interesting)

          by angel'o'sphere ( 80593 ) <{ed.rotnemoo} {ta} {redienhcs.olegna}> on Saturday April 01, 2017 @09:09PM (#54159051) Journal

          WTF, I have to escape less and greater inside of a code tag?

          There are no pointers involved, nor objects.

          The whole thing is for some strange reason "undefined".

          But actually it is pretty clear, why the C community made it "undefined" is beyond me, well: they did not want to impose a rule. But that is mere stupid.


              int s = 1;
              int b = 2; // s means small, b means big

              s < b; // true
              s++ < b++ // true ... usually, because here it starts, it is actually undefined, facepalm

              s++ < s++; // ok, here we have a point, obviously "it should be false" but it is undefined, and somehow makes sense to be undefined -- for me it makes no sense, in Java this is false

              s++ < s; // undefined in C, false in Java. // the original question
              C++ > C; // is only undefined because some guy thought, using the same variable in an expression involving ++/-- more than once is problematic. // actually they should simple have defined the behaviour. E.g. evaluate from left to right and be done with it

          • by mlyle ( 148697 )

            Always actually evaluating left to right is extraordinarily costly --- a lot of the trickery that compilers do to make things fast (CSE, interleaving loads & math, etc) don't work with it.

            And always actually having the same behavior as left to right, when not evaluating left to right in actuality, is hard to do and pick up any performance. Not for trivial cases like this, but because you might reach the same actual location in memory multiple ways (e.g. aliasing from pointer traversal).

          • s < b; // true
            s++ < b++ // true ... usually, because here it starts, it is actually undefined, facepalm

            That's well-defined. For someone arguing over the technicalities of C you sure don't seem to know the very basic rules.

            • It is not defined in which order the left and the right side of the less sign is evaluated.
              You should consult the manual of C/C++ - which ever you use - again.

              • It is not defined in which order the left and the right side of the less sign is evaluated. You should consult the manual of C/C++ - which ever you use - again.

                The order in this case does not matter, which is why it is well defined. The standard calls. It well defined, it is predictable what the outcome will be every time hence it is well defined. The expression 'C++ > C' is not well defined because the outcome cannot be predicted every time.

        • Well, at least one person noticed that the original poster was comparing two literal strings...

      • by Z00L00K ( 682162 )

        Interesting, but as I see it C++ has the bad features from both C and Ada and only have the positive side of allowing object orienting.

        However some stuff in C++ is quite confusing and does not make it very readable.

        • Re:Indeed (Score:5, Informative)

          by TsuruchiBrian ( 2731979 ) on Saturday April 01, 2017 @03:55PM (#54158433)

          It also has good features, many of which provide you with an alternative to the bad features of C.

          Constructors/destructors (RAII) > manual initialization/deinitialization.
          Smart Pointers (made possible by RAII) > raw pointers
          Polymorphism > function pointers
          Templates > macros

          If you are subscribing to a streaming movie service and you have the choice between netflix and a site that only allows you to watch "Armageddon (1998)", does it make sense to choose the latter because netflix has more bad movies? No of course not, because you don't have to watch the bad movies on netflix, and you can even choose only to watch movies better than Armageddon.

          C++ is netflix. Nobody watches all the movies. Everyone watches the movies that are good from their point of view (even though many of those people are just wrong).

          • Re: (Score:3, Interesting)

            by Demena ( 966987 )
            You are quite correct. Everyone uses different subsets of C++. The consequence of this should be obvious. Do not use C++ in any circumstances where code has to be maintained. The next maintainer maybe totally unable to deal with it being an expert (and using) a different subset of C++.
            • I don't think you can call yourself a C++ expert and be "totally unable to deal with" a C++ codebase that uses a different subset of C++ than what you would have used.

              You can certainly be a C++ expert and be totally unable to deal with a very poorly designed codebase, but that is true for every language (even C).

              Maybe there are more experts in the C language, because it is a simpler language and therefore an easier language to become an expert at. I would be totally in favor of using a simpler language for

          • there are no movies better than Armageddon.

    • "C++" > "C" (as long as > has not been overloaded..)

      Actually, it's undefined behavior.

      On most implementations, it is not true that "C++" > "C", but it is true that "C" < "C++".

      • Depends how you declare the arrays (and the implementation..)...
        char *cpp = "C++";
        char *c = "C";
        printf("C++ > C => %s\n", (cpp > c ?"yes":"no"));
        :-)
  • by zm ( 257549 ) on Saturday April 01, 2017 @01:38PM (#54158055) Homepage

    Code in assembly, then you can come back to my lawn..

    • With a halfway decent macro library [zerobugsan...faster.net], assembly's not too bad.
    • I wanted to take assembly in college. Alas, I went back to community college after the dot com bust. I couldn't get classes in the beginning because they were too many students. I couldn't get classes towards the end because they weren't enough students. When I showed up for the assembly class, I was the only student to show up and the class needed 20+ students to qualify for state funding. Since assembly wasn't a required course, I couldn't take it as an independent study class.
      • So, learn assembly in your free time.

        • So, learn assembly in your free time.

          It's on my to-do list. I'm currently going through an old compiler book to translate Borland C into modern C and learn Pascal to use the resulting Pascal compiler.

          • by JustNiz ( 692889 )

            >> I'm currently going through an old compiler book to translate Borland C into modern C

            err... why?

            • >> I'm currently going through an old compiler book to translate Borland C into modern C

              err... why?

              To learn C better. Also to learn how to write compilers. The used — and very obsolete — edition of the book was cheaper than the current edition ($5 vs. $70), and modern C compiler books are very expensive. Once I understand how to write compilers, I'll write a BASIC compiler in Python. I've been translating old BASIC games [atariarchives.org] into Python, which I've never gotten to work on my Commodore 64 as a teenager. Of course, Python extensions are written in C (or Cython).

              Keep in mind that I got an A.S. degre

              • You know you can load a binary into a debugger and view the assembly code?

                There's really not much to basic assembler. You have main memory, registers, and flags. You can move bytes (1, 2, 4, or 8 at a time, usually) between memory and registers. You can do basic arithmetic and bit operations in the registers, and those set the flags. You can make jumps (gotos) based on whether the the flags are set or not. That's pretty much it. The hard part is putting such basic instructions together to accomplish

                • You know you can load a binary into a debugger and view the assembly code?

                  Been there, done that. Commodore 64 in the 1980's and DOS debug in the 1990's.

              • by JustNiz ( 692889 )

                No, just reverse engineering existing code wont tell you what you really need to know, which is the theory behind what the programmer was thinking.

                Besides, the preprocessor may have been auto-generated with something like lexx/yacc which makes a giant state machine and will just give you a giant headache trying to figure it out from the code.
                You need to read up on tokens, lexemes, parse trees and other internal representations, once you understand those, you'll understand the meat and potatoes of a compiler

                • Besides, the preprocessor may have been auto-generated with something like lexx/yacc which makes a giant state machine and will just give you a giant headache trying to figure it out from the code.

                  I got the O'Reilly lexx/yacc book.

                  You need to read up on tokens, lexemes, parse trees and other internal representations, once you understand those, you'll understand the meat and potatoes of a compiler.

                  Those subjects are covered in the compiler book, which was previously used as a textbook in the early 1990's.

                  Also you're probably far better off looking at something like GCC than some old Borland crap.

                  The code in the compiler book was compiled with Borland C in the late 1980's. I have to modify the code to be ANSI C compliant for GCC to compile without error.

        • Me, I'd need a specific goal for that. I always found I could learn a *lot* faster within the structured classroom environment, and with the benefit of face-to-face conversations with people who understand the topic considerably better than I. And taking classes when you have a full time job - well, good luck with scheduling.

          • And taking classes when you have a full time job - well, good luck with scheduling.

            Depends on how motivated you are. I worked 60+ hours per week as a video game tester, taught Sunday school and took two classes per semester for five years. I even made the college president's list for maintaining a 4.0 GPA in my major. That was made possible by a $3,000 tax credit that George W. signed into law after 9/11 to help people transition into new careers. While I don't work as a programmer, understanding programming help me troubleshoot difficult problems in IT support.

      • I couldn't get classes in the beginning because they were too many students. I couldn't get classes towards the end because they weren't enough students.

        Did you do any classes on algorithms? If so, was binary search covered?

        • Did you do any classes on algorithms?

          That was probably under the "Data Structures" course.

          If so, was binary search covered?

          Binary search for the tree data structure.

          • Oh. Did you take any Gen Ed classes, like perhaps legendary literature or folkloric fantasy?

            • Oh. Did you take any Gen Ed classes, like perhaps legendary literature or folkloric fantasy?

              During my first tour through college, I took a half dozen lit classes (English Lit 1 & 2, American Lit 1 & 2, Women Lit and World Lit) and graduated with A.A. degree in General Education (1994). The only reason I graduated with G.E. instead of English is that the G.E. requirements didn't require a biology lab to dissect a frog. Because I completed an A.A. degree, I was only required to complete the major classes for an A.S. degree and graduated in Computer Programming (2007).

    • Coding in assembly is much easier than coding in a high level language and "doing it right".

      No idea where this Myth "if you can not do it in assembly you are not a real programmer" comes from.

      On the other hand, I pitty those who need to do assembly in 86k and its derivations.

  • by david.emery ( 127135 ) on Saturday April 01, 2017 @01:47PM (#54158073)

    At some point, the developer community will wake up to just how evil C -syntax- is, and how much it has contributed to bugs and security holes.

    • by david.emery ( 127135 ) on Saturday April 01, 2017 @02:00PM (#54158117)

      On the other hand, monkeys prefer C, because the programs they generate by jumping on the keyboard have the best chance to compile.

    • Re:They both suck! (Score:5, Interesting)

      by phantomfive ( 622387 ) on Saturday April 01, 2017 @02:05PM (#54158127) Journal
      What particularly don't you like about C syntax? I've always thought that the main security problem with C are caused by the lack of a decent buffer processing library, and a lousy string processing library. Fix those two things (and any person can do it in their own code!) and you've fixed the vast majority of C security bugs.
      • "=" vs "==", the presence or absence of commas or semicolons that substantially change meaning, the mess that is #include in large systems...

        Just look at any "obfusticated C" contest entry for egregious examples!

        Sure, you can learn and code around them. But at best that's a risk. And we have plenty of examples where those risks have made it to deployed systems. What was the Apple bug on certificates where a semicolon introduced a significant bug in certificate validation that was there for years?

        • "=" vs "==", the presence or absence of commas or semicolons that substantially change meaning, the mess that is #include in large systems...

          Those types of bugs are very rare, and #include was solved long ago with #IFNDEF _HEADER_NAME....

        • A good compiler will warn you if you use '=' in a test.

          • A good compiler will warn you if you use '=' in a test.

            ... and a better compile will allow you to make it a compile-time fatal error.
            Like this:

            gcc -O2 -Wall -Wextra -Werror foo.c

      • What particularly don't you like about C syntax?

        Function declaration syntax is demented, just to pull one thing off the top of a huge stack. Ever tried declaring an array of functions?

  • I use awk (Score:5, Funny)

    by jlowery ( 47102 ) on Saturday April 01, 2017 @01:50PM (#54158083)

    enough sed. don't bash me.

  • This just in, slashdot diminishes usefulness of site for a day in same tired April Fools joke they do every year!

    One editor was reported saying, "Yes, we've been beating this horse for twenty years now but rumors of the horse's demise many years prior have been grossly exadurated."

  • He favors automatic memory cleanup an trashes C for using marcos for it (which is indeed stupid) and favors destructors . But in that case he could just favor C# or Java. Both do the memory cleanup for you.

    Also his examples look very cluttered. It looks more like a C++ lover who try to bash C.

  • [...] "adopting a subset of C to smooth out C's rough edges" [...]

    FTFY — A little trick I picked up from John Carmack.

  • by JustNiz ( 692889 ) on Saturday April 01, 2017 @02:32PM (#54158231)

    Seems like his gripe is actually with STL and possibly curl's interface, not C++ per se.

    I like C++ (classes, exceptions etc) but generally avoid using STL except possibly for basic things like cout, strings and vectors. STL code becomes unreadable FAST, and quickly turns a simple problem into a giant pain in the ass, especially when debugging.

  • From the article:

    Set the handle to send a pointer to the struct. The handle expects a void *, so there’s an implicit cast from the struct’s pointer type to, effectively, nothing.

    A void pointer is NOT a pointer to nothing. At least it better not be. :-)

  • It's my most familiar language, back from when I was learning it on the schoolbus by reading K&R. I would still never choose C over a carefully-selected subset of C++ for a new project. There is just no advantage to keeping things more primitive except when it comes to very specific environments, like traditional Unix kernels. I think templates are very useful in limited doses and far superior than macros, inheritance is somewhat useful to almost any kind of CS problem, and the STL itself is a huge boon to software reliability and interoperability.

    Of course, I also have no qualms with Java, so....

  • by AaronW ( 33736 ) on Saturday April 01, 2017 @05:27PM (#54158625) Homepage

    In the 1990s I worked on a complex device driver for OS/2 for ATM networking (asynchronous transfer mode) [wikipedia.org]. The driver was around 100K lines of C++ code however only a subset of C++ was used. Surprisingly the use of C++ worked out quite well. We had an equivalent driver for Windows NT that was written in C that was over 300K lines of code. The C++ codebase was a lot more reliable and easier to work on, despite all the work that was done to make C++ work in kernel mode under OS/2. The C++ driver actually had more functionality than the C driver and it was faster as well with a smaller binary. Also, as I said, it was a subset of C++, especially in the performance critical code. The driver in question included the entire ATM signalling stack and implemented full LAN emulation support with both Ethernet and Tokenring plus it could emulate multiple networks (ELANs, equivalent to VLANs) simultaneously. When I implemented multiple ELAN support I was afraid it was going to be a nightmare, but due to the way it was architected in C++ I ended up only having to change a few lines of code, changing a pointer to the LANE class to an array of pointers.

    For the signalling stack and ILMI [cisco.com] C++ worked out especially well due to the event and message based nature of it and the various state machines. For LAN emulation it made it easy to support both Ethernet and Tokenring by having a few virtual functions in the main LANE class.

    There was no exception handling support and none of the more complex C++ features were not used. It used templates but that was also somewhat limited.

    Having destructors was also quite nice, making it easy to clean up resources.

    Despite being C++, debugging wasn't too bad though at the time the OS/2 kernel debugger basically ran at the assembly level.

    If the infrastructure is in place I can certainly see using C++ in the kernel and device drivers.

    • If the infrastructure is in place I can certainly see using C++ in the kernel and device drivers.

      Its already been done. At least one of the L4 microkernels (Fiasco?) is implemented in C++. You don't lose code efficiency doing it in C++, if you know what you're doing in C++.

  • well there is a ++ in the name so.....

  • by woboyle ( 1044168 ) on Saturday April 01, 2017 @10:50PM (#54159223)
    I have been writing C since the early 80's and C++ since the early 90's. For large-scale robust systems, C++ is the way to go. It provides for greater degrees of abstraction, debug-ability, and clarity of intent. I only use C any longer for kernel development.
  • Well, duh - it is (Score:4, Informative)

    by johannesg ( 664142 ) on Sunday April 02, 2017 @04:23AM (#54159591)

    C++ is much better than C. It's much greater expressiveness makes it easy to clearly formulate what you are doing, and in far fewer lines of code too. Exceptions free you from all that tedious boilerplate, where every function call basically expands into three lines: error=function();if (error) handle_error (error);. RAII makes resource handling painless. It's massively more powerful standard library provide instant access to lots of useful datastructures and algorithms, and unlike C it's all typesafe too.

    Is it hard to use? Hardly. I find C hard to use - just imagine having to write an application that uses strings, it'll be one giant mass of mallocs, strcats, strcpys, frees (don't forget any!), and will invariably end in buffer overflows and lost memory. Oh, and it will probably have a whole bunch of gotos for what they laughingly call 'resource management', Dijkstra's 1968 paper notwithstanding.

    Do I disagree with all the criticism, then? No - but the horror stories that get posted here do tend to be worst possible cases, which pop up once in a very long while, rather than the daily occurrences some people make them out to be. It's been... I don't know, half a decade or so? since I last saw one of those horrifying template errors - and it's not for lack of templates in my code. It's not really a hard language either - sure, you _can_ write unreadable statements, but you can do that in any language so that doesn't mean much. It also gives you the tools to write much, much clearer code.

    I always roll my eyes when people mention needing a 'cut-down C++'. That's lack of understanding, usually mixed with a liberal dose of unwarranted fear, and better advise would be "use common sense". For example, there is nothing wrong with overloading operators, but common sense indicates one should not change the meaning of those operators. Having your own number-like class is fine (for example, for complex numbers, bignums, money, whatever), and overloading operators for it is an excellent idea. Using operator+ to paint a widget or retrieve data from a database - maybe not so much.

    So, yeah, C++ is an amazing language. Hmm, that makes me wonder if there will be an article on Medium now, revealing that someone on Slashdot just said that. I don't know that website, maybe they are not into clickbait so much...

    • gcc added something called "cleanup attribute" which is essentially destructors in C++. That replaces "goto" in the case you described. I really hope they will put it in the standard at some point.

  • by w3woody ( 44457 ) on Sunday April 02, 2017 @08:52AM (#54159867) Homepage

    I first started using C++ back in the 1980's.

    I am a huge fan of classes. When C++ was basically a preprocessor for C which introduced the class keyword, I thought it was pretty cool.

    When exceptions were introduced to the language I thought C++ was fairly complete as a language. If from there the designers of C++ had addressed the fragile base class problem, lambdas and some form of introspection, I think C++ would have been a fantastic language.

    Instead, we got templates. I'm not a fan of templates.

    And when we got the standard template library, I thought someone was smoking crack. Using the left shift and right shift operators to mean "input" and "output"? Really? Really?!?

    When I write C++ I try to stick to using a subset of C++ which includes classes and exceptions. I use templates sparingly, only when they are really needed, and I refuse to use the C++ left-shift and right-shift operators. (I really feel like the person who designed that thought "how cool; we can override a shift operator to mean input and output!" But just because you can doesn't mean you should, and now we're stuck with this bit of syntactic bit of bullshit.

    We're finally getting around to lambdas, though too late: Apple has already wedged blocks into a non-standard extension. And I'm not holding my breath on introspection or on fixing the fragile base class problem simply because the run-time implementation recommendation for classes way back in the late 1980's has become a baked in de-facto feature. (Sadly it would have been relatively easy to solve by introducing link-time assignment of the indexes in the virtual table pointer; that way, as the base class is recompiled the index references for the methods in the virtual table could be reassigned at link time. This also solves fragile access to public class fields; simply replace them with a standard getter and setter method which is accessed via the virtual table.)

  • by Qbertino ( 265505 ) <moiraNO@SPAMmodparlor.com> on Sunday April 02, 2017 @11:50AM (#54160239)

    C++ done right is do vastly different from C that debating which language is better is beyond silly. This goes threefold if you look at C++14 programmed with the GSL - the right way to do C++ these days.

    In a nutshell C is assembler 2.0 and C++ is assembler 3.0. C++ has massive inner api advantages over C that C tries to compensate for with libs such as boost.

      Yet build with C++ without knowing what you are doing and of course you'll produce bad software. With C you simply won't get anywhere.

    Wether you use one or the other these days is often a matter of personal preference more than anything else. C++ has massive ready-made power with the responsibilty that comes with it. Any programmer looking at these PLs will see the difference and adapt his style of coding accordingly.

"Protozoa are small, and bacteria are small, but viruses are smaller than the both put together."

Working...