• (cs) in reply to Zlodo

    Another benefit to operator overloading in C++: template algorithms do not have to distinguish between intrinsic and user-defined types.
    For example, the standard for_each algorithm (modified slightly from the SGI implementation):

    template <class InputIterator, class Function>
    Function for_each( InputIterator first, InputIterator last, Function f)
    {
       for (; first != last; ++first)
          f(*first);
       return f;
    }


    because function calling, pointer dereferencing, comparison, and incrementing are overloaded this algorithm works for standard containers and functors, as well as for C-style arrays and functions.

    In effect, it is the same argument as before -- there is a consistent syntax for similar operations. My point is that it doesn't only increase the readability, but also the utility of the code.

  • (cs) in reply to RevMike
    RevMike:
    Anonymous:
    > We'll use ">"  for "pairwise multiply" (we'll return a vector) then we'll drink a beer
    > and laugh at the poor saps who'll be maintaining our code when we move on.

    For those who bash operator overloading, I only have the following reply, in Java:

    public int multiply (int v1, int v2)
    {
         return v1 + v2;
    }

    Yes, exactly.


    Why would anyne do that?  We have a built in integer multiplication operator, and the method you describe isn't even a static method.  This makes very little sense...

    Maybe what you really wanted to say is this...

    public class MyInt
    {
        private int theValue;
        .... constructors and other methods skipped.

        public int multiply(MyInt v2)
        {
             return theValue + v2.theValue;
        }
    }

    The problem with operator overloading - and even C++ fans admit this - is that it is possible to overload an operator in an unexpected way AND it not be obvious to a maint. developer that there is even a method call involved.  Java, by eliminating operator overloading (ignoring the String +), insures that the developer always knows that there is a method call involved.


    You get bonus for good effort. However, in practice, the same hypotetical maintenence programmer would expect the "myclass.multiply( myotherclass)" call to be just as fundamental and correct as a "myclass + myotherclass" call. Again, it has nothing to do with the facilities, it has to do with how they're used. Overloading can be misapplied by introducing unexpected functionality, and so can notmal functions or methods. As several users here, including me, have already pointed out, yours is a hypothetical and rethorical objection (and Java market speak) exceedingly rarely seen in live, non-newbie code.


    brazzy:
    Zlodo:
    Not to say that it doesn't happen, but it doesn't seem like such a common occurence as people seem to make it.

    The WTF I see most often in C++ code seem to be more lke stupidely huge classes, useless classes, stupidely huge functions, juggling with pointers, duplicated (but different) implementations of the same things, and generally doing simple things in an hopelessely convoluted way.

    Note that all of these WTF except the pointer stuff can be, and probably are, done with any OO language.



    As someone who programs Java for a living, I can tell you that that is EXACTLY what's being done with it (except for most of the pointer juggling, of course).


    However, I still shudder at the thought what people writing that kind of code could do when they are given operator overloading and get excited about its possibilities...



    Perhaps that is what Sun (perhaps wisely given the user base alluded to in the post?) amputeed certain fundamental facilities from Java then. Face it, the difference between C++ and Java, that again and again rekindles the holy wars even here, is one of different philosophies, or more correctly, trust. Java is (was) aimed at the lowest common denominator, which is the typical corporate, market/marketing-oriented worldview; C++ is targeted for the power programmer, which is the technician and power user's worldview.

    As I've pointed out befire, neither is better. Both languages are aimed at different crowds for different purposes. They are both better than the other for certain tasks, as are (almost) all languages.
  • (cs) in reply to Mikademus
    Mikademus:
    Face it, the difference between C++ and Java, that again and again rekindles the holy wars even here, is one of different philosophies, or more correctly, trust. Java is (was) aimed at the lowest common denominator, which is the typical corporate, market/marketing-oriented worldview; C++ is targeted for the power programmer, which is the technician and power user's worldview.


    Face it: that's what the C++ fans have to keep telling themselves to be able to bear that mess of a language, while Java  programmers bask in its simple elegance
  • (cs) in reply to brazzy
    brazzy:
    Face it: that's what the C++ fans have to keep telling themselves to be able to bear that mess of a language, while Java  programmers bask in its simple elegance


    I'm not certain if that is attempted humour, childishness or plain myopic blindness, but really, c'mon. Grow up.
  • (cs) in reply to Mikademus
    Mikademus:
    brazzy:
    Face it: that's what the C++ fans have to keep telling themselves to be able to bear that mess of a language, while Java  programmers bask in its simple elegance


    I'm not certain if that is attempted humour, childishness or plain myopic blindness, but really, c'mon. Grow up.


    It was an attempt to poke fun at YOUR myopic blindness which, perhaps not unsurprisingly, you are unable to perceive.

    Calling Java's design the "lowest common denominator" is nothing but a desparate attempt to make C++ seem superior. A more fitting description is that Java was designed with the goal to let the developer concentrate on the complexity of the application rather than the complexity of the language, to maximize productivity rather than feature count.
  • Monika Icon (unregistered) in reply to Manni

    I suspect that the use of vfprintf and va_list rather than sprintf suggest the documentation would only display functions starting with 'v', so there was no hope of finding ones earlier in the alphabet!


     

  • Tennessee J. Windage (unregistered) in reply to brazzy
    Face it: that's what the C++ fans have to keep telling themselves to be able to bear that mess of a language, while Java  programmers bask in its simple elegance

    And they've got a lot of time to bask, waiting for their code to run.

    Java has a lot of very severe problems. Being trapped in a VM is one. Designed-in hostility to interoperability is another: Java doesn't like to talk to anything not also written in Java (compare the horrors of JNI to .NET COM interop, and weep). The absurdly over-orthogonal standard library is a third: It looks like it was designed by a diligent but unimaginative grad student, who finalized the design on paper before coding anything, and was too pigheaded to fix the design when it turned out to be clumsy and painful to use in practice. Ever tried to format a date in Java? You need, what, four different classes and nineteen enums? Compare to strftime(): I rest my case. Formal "elegance" at the expense of usability is not a win. It's not a sculpture, it's a tool. People use it to do things. Java is like somebody making a spherical hammer because spheres are "geometrically perfect". Who gives a crap? Geometrical perfection is not a sane design goal in that case. The goal is to make something you can hold in your hand and bang nails with.

    I've noticed that most of the rabid Java fans on the net are either trolls who don't believe what they say (and I'm all in favor of that), or else idealistic undergraduates who don't know what they're talking about.

    When Java is used in industry, it's almost invariably forced on developers by clueless managers. Any team can use Java for one project, learn from their mistake, and move on. If they use it for a second, they may be fools, or there may be a dumbass manager somewhere who got drunk on buzzwords, but it's a plague ship either way.

    Java's natural environment is in-house development at banks and such. That kind of work is a living death in any case, whether you do it in PL/1 or COBOL or Java or whatever. It's idiotic to compare it to C++, because it's not competing with C++. It's competing with Visual Basic and COBOL. You may enjoy finding yourself in that kind of company. Personally, I wouldn't.

  • (cs) in reply to Tennessee J. Windage
    Anonymous:
    Face it: that's what the C++ fans have to keep telling themselves to be able to bear that mess of a language, while Java  programmers bask in its simple elegance

    And they've got a lot of time to bask, waiting for their code to run.


    yawn  Pull the other one, it's got bells on.

    Anonymous:
    Java has a lot of very severe problems. Being trapped in a VM is one. Designed-in hostility to interoperability is another: Java doesn't like to talk to anything not also written in Java (compare the horrors of JNI to .NET COM interop, and weep).


    The quote is just too good not to repeat it:
    "If you were to copy a term paper that you got from a kid who graduated
      several years earlier, you are likely to fix all the areas the teacher
      marked in red pen while you are doing it" (RevMike)

    BTW, what are C++'s interoperability facilities?

    Anonymous:
    The absurdly over-orthogonal standard library is a third: It looks like it was designed by a diligent but unimaginative grad student, who finalized the design on paper before coding anything, and was too pigheaded to fix the design when it turned out to be clumsy and painful to use in practice. Ever tried to format a date in Java? You need, what, four different classes and nineteen enums? Compare to strftime(): I rest my case.


    You mean you admit you're wrong?

    new SimpleDateFormat("
    yyyy-MM-dd").format(date);

    Anonymous:
    I've noticed that most of the rabid Java fans on the net are either trolls who don't believe what they say (and I'm all in favor of that), or else idealistic undergraduates who don't know what they're talking about.

    (more frothing-at-the-mouth nonsense)


    Well, I've noticed that most of the rabid java haters on the net are idiots who base their rants on carefully nurtured misconceptions and are motivated by an inferiority complex because Java is or is becoming more successful than their favourite language.
  • Tennessee J. Windage (unregistered) in reply to brazzy
    "If you were to copy a term paper that you got from a kid who graduated several years earlier, you are likely to fix all the areas the teacher marked in red pen while you are doing it"

    Interoperability had been done before Java happened. COM already existed, as a matter of fact. Gosling had an existing A paper in front of him, and he cribbed from the class idiot instead. NIH, was it? Ignrance? Ego out of control? Who cares? He screwed up.

    In either case, you have chosen to use the original error-ridden paper rather than the corrected version. That's stupid. I'm not a professor grading these guys; I'm a practitioner deciding which tool to use. I couldn't care less who "did it first". Reusing and refining other people's ideas is good engineering. Reinventing the wheel is a wonderfully instructive and absolutely necessary exercise for students, but we don't do that in the real world if we can possibly help it. We have deadlines, we have customers. Hardware engineers do the same thing. They use off-the-shelf parts wherever they can.

    In fact, the CLR is still pretty bad. They didn't fix enough of the mistakes. But it's less awful than Java. You know, MS isn't exactly a world leader in language design. By any standards but Sun's, they're the village idiot. It takes massive brain damage to design a worse language than one of theirs.

    what are C++'s interoperability facilities?

    COM, shared libraries, etc., depending on platform. Do you have any idea how simple and universal a COM interface is? C/C++ interoperates very happily with compiled code written in other languages. Of course, it's easy for them, because C/C++ compiles to native code. Ritchie made the right decision on that from day one, and it's still paying off thirty-odd years later. Java isn't like that. Java wants everybody else to be Java, too. This, again, is the kind of naïve stupidity that characterizes Java from start to finish. The world is full of things that aren't Java. Kernighan famously addressed this same issue in "Why Pascal Is Not My Favorite Language", over a decade before Gosling sat down and demonstrated his inability to learn from the mistakes of others.

    Lack of interoperability, even more than laughable run-time performance and pointlessly obstructive orthogonality-for-its-own-sake (which you mistake for "elegance"), is what killed Java in the marketplace for serious programming tools. They've also got a problem with being committed to OOP at too fundamental a level. OOP is a great way to approach a lot of problems, but it can be a real straitjacket sometimes. I wouldn't care to live without generic programming, much less components. Again, Java is long on ideology and short on practical reality: It is simply moronic to declare that OOP will always be the best tool for every task you'll ever work on.

    I'm glad to hear they fixed the date formatting imbecility. Took 'em a decade, did it? Or was it there all along, hidden in an unsorted pile of ill-formatted HTML documentation with no search facility other than grep?

    And when are they going to replace the rest of the library?

    Java is perfectly irrelevant to me: I'm not an undergraduate, and I don't write paint-by-numbers data-entry UIs at a bank. Java has no other legitimate uses.

  • (cs) in reply to Tennessee J. Windage
    Anonymous:

    what are C++'s interoperability facilities?

    COM, shared libraries, etc., depending on platform. Do you have any idea how simple and universal a COM interface is?


    (loads mor ranting)


    COM as a shining example? BWAHAHAHAHA!!! That's rich, more of that, please!

    This is pointless. I have better things to do that correct all your misconceptions and self-contradictions that clearly prove that you don't even know what you're talking about. You are either a troll, a paid Microsoft shill, or so hoplessly unable to conceive anything outside your set ways that it makes no difference.

    Go ahead, declare yourself the winner, go back to your tinkering and let us real programmers get work done.

  • Tennessee J. Windage (unregistered) in reply to brazzy

    Pop quiz: Explain what a COM interface is. The data structure. Explain the calling convention issues. Then explain "dual" interfaces, including "early binding" and "late binding" via IDispatch.

    You went blank on the very first question, didn't you? Do you even know what COM is? What it's used for? You're miles out of your depth.

    Another teenage Slashbot with a head full of buzzwords. No doubt you're reading this in Mozilla. You've never heard of XPCOM, have you? Read up on it. The Mozilla guys liked COM so much they went to the trouble of implementing a cross-platform clone for their own use.

    My gut feeling is that they teach the intro CS course at your school in Java. You're a sophomore now, and this semester they tried to teach you C or C++. It scared you stiff, because you're still pretty green. Learning your second language is harder than learning your third, because you haven't begun to learn to distinguish between language features and fundamental concepts. That distinction is one of the reasons why it's important to know several languages, the more disparate the better. When you've mastered LISP, Perl, C, C++, SQL, and one or another of the more or less dynamically typed, more or less OOP languages like JavaScript, Ruby, or Python, and when you've at least been well exposed to one assembly language or another, you'll know some important things about programming that you don't (and can't) know now: You'll know that there are a lot of ways of thinking about problems in programming, and a lot of ways of expressing those thoughts at many different levels of abstraction, and that different problems are often best solved with different tools. You'll have a good start on being able to choose the right tool, too.

    A self-described "programmer" who has mastered only one language is a grossly incompetent fraud. He's either a newbie, or a hopeless moron who lacks all curiosity. If you haven't got a will to learn new things, this field has no place for you. Change your major to sociology or something before it's too late.

  • (cs) in reply to Tennessee J. Windage

    Great. 15 posts in after registering and I'm getting dragged into a repetitive holy war by what looks like a crusading troll.

    @Brazzy, C++ is designed for power and for use by people with the mindset and judiciousness to use that power, with the accompanying dangers. Java on the other hand is feature- and power-reduced to keep the programmer in relative safety.

    By design and in consequence C++ and Java are used for different things. Comparing them is not really productive for serious programmers

    • you will need to deal with both of them --and more languages yet to boot!-- unless you're planning to do one thing only until you drop dead from boredom or misguided idealism. All real programmers as traditionally defined, chose languages after the problem at hand. Bad programmers try to adapt the problem after their preferred language. Problem is that real programmers, as defined by the true hackers of yore, have always been scarce and the ratio is decreasing. I have no issues except aesthetic with Java, and I use the language, along with several others, what I do have issues with is a common type of Java programmer: quite often evangelistic to the extent where shoehorn mentality starts to reign and adaptability and pragmaticism dissipate.

    Now stop being a child and get pragmatic. By your arguments you haven't proven to be the "real programmer" you claim. And unless you shape up, which entails relaxing that high-windedness a bit, you'll likely never be.


    And Tennessee J. Windage, you're obviously very knowledgeable. Exept about feeding and being agitated by, if not trolls, then at least ogres. Maxim: Tranquility --> Zen Code. Also, Sociology can be a great and developing subject unless you have idiots for teachers. Only don't expect a gainful employment from it :)
  • (cs) in reply to Mikademus
    Mikademus:
    All real programmers as traditionally defined, chose languages after the problem at hand.


    Almost, but not quite right.

    The choice of language - and any other part of the environment - takes into account both the problem and the environment into which the solution will be installed.  Even if Ruby is - on its own - the best tool to solve a problem, I wouldn't recommend it to a company that has only .Net in house unless Ruby was so much better than the alternatives that it justified the hiring of special talent to maintain this one app.

    When planning to implement any application, the architect needs to first consider what technology stacks provide for acceptable solutions, and then balance the elegance of any particular stack with the cost to support that stack within an organization.  A good solution that leverages the skills already on site is better than a more elegant solution that requires brand new skill sets.
  • (cs) in reply to Mikademus

    Mikademus:
    I have no issues except aesthetic with Java, and I use the language, along with several others, what I do have issues with is a common type of Java programmer: quite often evangelistic to the extent where shoehorn mentality starts to reign and adaptability and pragmaticism dissipate.


    Except that in this thread it is the C++ programmer who has an evangelistic shoehorn mentality and is unable to display anything except vitrolic hatred and childish, unfounded arrogance towards Java. It is not I who is the crusading troll here.

    Mikademus:
    And Tennessee J. Windage, you're obviously very knowledgeable.

    About his language of choice, perhaps, but he is very obviously very ignorant about the language he attacks with such agression. He had no concrete arguments at all save one, which I prompty showed to be simply wrong.

     

  • (cs) in reply to brazzy

    Well, I for one, think that these recurrent holy wars between C++ and Java are unfortunate and misguided. Both are major languages in common use today, but for different areas of application. To this you retorted ad homined with that this is what C++ programmers comfort themselves with while watching their world being overtaken by Java - an immature, bipolarised, aggressive and partisan tauntrum. Of course Java has grabbed programmers from C++ since it solves certain problems, if not better than easier, than C++, just as Python has grown on the expense of C, and just as Ruby is doing atm on the expense of Java. This is as it should be: problems are to be approached through the tools that best address them. And C and C++ still address many problems significantly better than the alternatives.

    If anything this particular holy war serves to emphasise and illustrate that it is really about particular mindsets. On the one hand you have the typical die-hard C/C++ advocate which is a tech/hacker kind of guy who likes to know and control in detail what he's doing, and on the other hand you have the typical Java guy who doesn't care about implementation details or understanding or controlling what is going on under the hood. In other words, in a way, a reprise of the 70 and 80's "hacker" vs "user" wars.

  • netch (unregistered) in reply to Clinton Pierce
    Anonymous:
    Not to defend the code, or the technique but I always like finding a bright side of things... I'd like to point out that the general technique has one advantage that sprintf does not: you can allocate exactly the amount of memory that you need to hold an arbitrarily formatted string. sprintf(buf, "%f", f); // How many bytes for buf?


    Yes, _if_ it _were_ used in this code. But it doesn't allocate string of needed size, it uses static buffer...

    And, the old well-known method to calculate needed size (in absense of snprintf() or funopen()) is to open The File and write data to its. But in good implementation The File is /dev/null (NUL in MS OSes), not real file on disk!

    Anyway, the code in the article is the worst ever seen...

  • vDave (unregistered) in reply to Omnifarious
    Omnifarious:
    Anonymous:
    *(char*)*va_arg( marker, char * );
    is needed to compensate for
    va_start( marker, first );

    The malformed va_start means the first va_arg will return the char* format. The line should read:
    va_start( marker, format);

    As to why he is casting and dereferencing it... well... you're on your own.

    And, of course, the amusing thing is that the whole 'skip the char *' bit isn't actually portable. va_args isn't for reading arguments that the compiler knows are there, and if I'm not mistake, its result is undefined if you do. For all you know, the compiler could be passing all the arguments it knows the exact signatures for in registers.



    Ha!

    This was my first thought upon reading this (well, the top portion, at least) as well.  "Better hope this is in a debug build with no optimizations!"

         -dave-
  • Marcos Dione (unregistered) in reply to Whackjack

    What's up with all the {} embedded in there? Please tell me that's Alex's new way of showing a snippet...

    I think those {} are:

    • attempts to comment a la pascal.
    • as they are empty code blocks, to `clean up´ the namespace.
    • waste some time just in case the previous statements were not executed.
    • mark thew code as important.
    • some alien put them there trying to inject a virus, converting the program into a trojan.
  • Kuba Ober (unregistered) in reply to RevMike

    Most likely, you'd want to have Vector::operator*(const Vector &) be private and unimplemented, so that it cannot be used, in order to avoid ambiguity.

    If you want to be brave and have got good documentation, in place, it's doable to have cross product say as operator^ and scalar product as operator%. As long as they are not * so that people won't make wrong assumptions. Oh, while we're at it, never have a non explicit from-scalar constructor in your vectors ;)

    That's what I did in my algebra code.

    Cheers, Kuba

  • (cs) in reply to Chris

    Anonymous:
    I particularly liked his filehandle naming convention: FILE1 FILE11 FILE111
    Well this is very obvious to me: he habitually  uses the base-1 numbering system. And he prefers to start counting at 1 instead of 0.

    Or maybe he was using tally marks. When he got to the fifth filehandle, it probably would have been named FILE_; then the sixth one would have been FILE_1; and the tenth would have been FILE__; and the eleventh would have been FILE__1.

    This is pretty standard where I work (Hell).

  • (cs) in reply to IQpierce
    IQpierce:
    Anonymous:
    I particularly liked his filehandle naming convention: FILE1 FILE11 FILE111
    Well this is very obvious to me: he habitually  uses the base-1 numbering system.


    So does Microsoft Excel '97:
    http://support.microsoft.com/kb/177634/en-us
  • anonymopitus (unregistered) in reply to Zlodo

    This is not C++. C99 supports declaring variables in between statements.

  • silkio (unregistered) in reply to Whackjack
    Whackjack:
    What's up with all the {} embedded in there?  Please tell me that's Alex's new way of showing a snippet...


    it's probably a place where he could set a breakpoint.
  • Wow Guy (unregistered) in reply to RevMike

    Excellent bad solution!

  • Harring (unregistered) in reply to Whackjack

    The {} is trnslated by the compiler as a 'no-op', so it is used here to optimize the code - LOL

  • Harring (unregistered) in reply to anonymopitus

    I am not even sure if it is 'C' at all. LOL

  • Steve H (unregistered)

    Thanks everyone.  I'd be freaked out and start to re-learn my C/C++ after seeing that code, if you guys did not back me up.

    I kinda know what the code is saying, but wait...

      // this is required, or it will not work for some reason
      *(char*)*va_arg( marker, char * );

    Why would you cast a function call?  Hm... I've seen (void*)foo_call(parameter_foo); before, but... what the!?  do I really know C/C++?  OMFG I don't know anymore... *sob*

    Good thing you guys pulled me back...

     

    CAPCHATEST says it all:  CLUELESS

  • Fizzl (unregistered)

    What the bloody hell? The guy knows how to use argument lists for functions, but has never heard of sprintf?

  • Mike (unregistered)

    I'm new to C++. For a project I'm working on, I needed to construct a string in printf style so I googled "printf to string" and this was the first result. So thank you, The Daily WTF, for pointing me to the sprintf function :)

  • Sebastian Ramadan (unregistered)

    The author could have read a book to learn C, the manuals for printf to discover sprintf (and better yet, snprintf), va_start, _mktemp, fopen, fseek, ftell, read, etc to discover serious issues with this code, but he/she clearly isn't particularly good at reading. As a result, he/she should be a FRUIT PICKER rather than a programmer. Argh! KILL IT WITH FIRE!

    Captcha: validus. This code fails the validus tester.

  • JarrodErede (unregistered)
    Comment held for moderation.
  • cbd gummies (unregistered)
    Comment held for moderation.
  • HildamUp (unregistered)
    Comment held for moderation.

Leave a comment on “Printf to String”

Log In or post as a guest

Replying to comment #54632:

« Return to Article