5 ms·
I don't think this is good advice, although I don't agree with you being downvoted because of that. C++ is a much more complex language than C. The things you
by MattPalmer1086 4y ago
I don't think this is good advice, although I don't agree with you being downvoted because of that.
C++ is a much more complex language than C. The things you need to worry about in C are far fewer than in C++.
- zabzonk 4y agook. a small challenge - read character input of undefined length, and then print the input out backwards. i guarantee the c++ code will be easier to write and understand than any c code.
- camel-cdr 4y agoThat actually sounds like a fun way to explore different programming languages. Especially if you extend it to inputs that may take up more memory then you've got on your computer (let's say 100GB) and at least reasonably fast. I suppose it'd kinda trivial if you read the input from a regular (seekable) file, but if you actually read the 100 GB from stdin then this could get quite complex.
- zabzonk 4y agofinding good teaching examples is hard - here's one i prepared earlier https://latedev.wordpress.com/2011/07/28/writing-a-real-c-program-part-1a/ https://latedev.wordpress.com/2011/07/28/writing-a-real-c-pr... but could not complete as i was struck down with terrible depression, and then my mum & dad needed looking after, and then...... perhaps i will start it up again, now it is just me, and not exactly happy, but not depressed.
- johndough 4y ago> i guarantee the c++ code will be easier to write and understand than any c code. That will depend on how you define "understand". For a superficial level of understanding, you might be right. But the C++ code will make use of many concepts that would take a while to explain, for example references, classes, inheritance, templates, operator overloading, STL, and probably a bunch of other things I forgot.
- erik_seaberg 4y agoThere are books explaining those things, and as a professional I can expect to amortize the effort over years of other projects.
- wizzwizz4 4y ago#include <stdio.h> #include <stdlib.h> int main() { size_t len = 0, cap = 0; char *buffer = NULL; int c; while ((c = getchar()) != EOF) { if (len >= cap) { cap = (cap << 1) + 1; { char *newbuf = realloc(buffer, cap); if (!newbuf) { fprintf(stderr, "Could not reallocate to %zu. Printing what I've got.", cap); break; } buffer = newbuf; } } buffer[len++] = (char)c; } while (len --> 0) { if (putchar(buffer[len]) == EOF) { fprintf(stderr, "Output failure."); return 1; } } free(buffer); return 0; } Most of the verbosity here is in correctly handling errors, something that isn't much easier to do in C++. (Be warned: I haven't tested this code.)
- zabzonk 4y agoor in c++, simply call getline? i haven't traced thru your code, but i would not be surprised if there were errors in it, having written similar stuff myself. compare with using std::string and std::getline - easy to use and battle-hardened.
- wizzwizz4 4y agoHow does getline handle the out-of-memory condition? How do I avoid leaking memory – is that handled by std::string's RAII destructor? To detect the end-of-file condition, there's something about a failbit, but I'm only four pages of documentation in, so I don't know what that is yet. What would the equivalent code look like in C++, handling EOF and OOM conditions appropriately?
- blackpill0w 4y agoprobably std::string would throw std::bad_alloc, and there is also the failbit flag which std::getline sets
- zabzonk 4y agoif memory is exhausted, then getline throws a bad_alloc exception. if end of fileis reached (which i am not sure your code deals with correctly) then getline returns a stream in a bad state. so something in outline like this (syntactically correct. std:: omitted for brevity, but probably not what you would really write): string input; try { if ( cin.getline ( input ) ) { // ok read input, do something with it } else { // some sort of predictable error - look at state of cin to diagnose EOF } } catch (...) { /// something terrible happened - as hard to recover as it would be in c }
- a1369209993 4y agoIt's unclear exactly what you mean by "backwards" (and some interpretations like "print UTF-8 characters in reverse order" are infamously literally impossible[0]), but here's a straightforward/naive version (bytes in each line): #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <sysexits.h> #define die(E,...) ({ \ fprintf(stderr,__VA_ARGS__); \ exit(E); }) void reverse(char* a,size_t z) { for(; z>=2 ;a++,z-=2) { char t=*a; *a=a[z-1]; a[z-1]=t; } } int main(void) { size_t z=16,i=0; char *a=malloc(z), *p=0; for(;;) { for(;;) { ssize_t n = read(0,a+i,z-i); if(n<0) die(EX_IOERR,"input error: %m"); if(n+i==0) exit(0); if(n==0) die(EX_DATAERR,"error: %zu bytes of garbage at end of file",i); p = memchr(a,'\n', (i += n) ); if(p) break; if(i > z/2) { a = realloc(a, (z = z+z/2) ); if(!a) die(EX_OSERR,"realloc(%zu bytes): %m",z); } } while(p) { reverse(a,p-a); fwrite(a,p-a+1,1,stdout); memmove(a,p+1, (i -= p-a+1) ); p = memchr(a,'\n',i); } } } This produces: $ ./a.out cat tac warning: incompatible implicit declaration of built-in function noitcnuf ni-tliub fo noitaralced ticilpmi elbitapmocni :gninraw naïve resumé �muser ev�an > i guarantee the c++ code will be easier to write and understand than any c code. Put up or shut up, as the saying goes. At the very least it ought to be easy to abstract out some of the memory allocation and file handling to use C++ builtins, and I'd be interested to see what other improvements you can manage. Edit: 0: Exercise for the reader: consider the input "abXc", where 'X' is some as-yet-undefined codepoint that will, at some point in the future, be defined as either a combining diacritic, or a standalone character. If 'X' is a character, the output should be "cXba", but if it's a diacritic, the output should be "cbXa". The information about which (mutually-exclusive) output is correct does not exist yet.
- deleted 4y ago[deleted]
- blackpill0w 4y ago>C++ is a much more complex language than C While this might be true, generic containers, sane strings, RAII and the possibility of not having to deal with pointers makes C++ an easier language to work with. You certainly need to worry about much less things long as performance is not a priority.
- bsder 4y ago> sane strings So, explain to me why every C++ program always has its own String implementation? > long as performance is not a priority. Then C++ is a disastrous choice. Almost anything is better.
- zabzonk 4y ago>So, explain to me why every C++ program always has its own String implementation? i have no idea where you are reading about c++, but every c++ program i have read or written in the past 20 years or so does #include <string> std::string greet = "hello, world"; the full-stop in front of the hash is something with HN, not me or c++, and only seems to show up when editing.
- blackpill0w 4y ago>So, explain to me why every C++ program always has its own String implementation? *saner :) >Then C++ is a disastrous choice. Almost anything is better. True, C and C++ are most of the time not the right tool for the job nowadays. But, if it's just a project that you're working on in your free time, it wouldn't harm to write it in your favorite language. I write in C++ a lot even if I could do the same thing much easier in other languages.
- wizofaus 4y agoThe last sentence doesn't really follow from the previous one. C++, like other higher level languages, has complexity built in because it takes care of things that in C you have to take care of yourself. I can't imagine any serious C++ project becoming "less complex" to work on by rewriting it in C.
- uecker 4y agoI personally found it very relieving when I switched from C++ to C. (and I also rewrote some stuff, it did not get more complex.) I find readability of modern C code much better than C++. In C you see what you get: no templates, overloading, virtual inheritance, namespaces, exceptions, references etc you need to keep processing in your head just to understand what is going on.
- wizofaus 4y agoI don't doubt that can be true - but there are plenty of common operations like concatenating strings or converting between strings/numbers that are a good deal simpler to write and understand in C++ than they are in C. In particular there are far more ways to get them wrong in C!
- uecker 4y agoIf you code them by hand, then yes. If you a library, then it is the same. It is certainly true that the C++ standard library provides more functionality out of the box.
- wizofaus 4y agoAlmost any C library function that deals with strings is going to be more complex to use due to the lack of automatic memory handling, necessary for any use case where the max. size isn't sufficiently well-known at compile time for it to sit on the stack. I'd accept something like "atoi" or "strtol" is pretty simple to use (and hard to get wrong), but hardly win any awards for obviousness. And the less said about the need (or at least strong tendency) to use sscanf for more complex parsing (hexadecimals etc.), the better.
- WalterBright 4y agoYou can learn C in a few days. It takes 10 years to learn C++. My experience, anyway.
- zabzonk 4y agoi respect your opinion, but for example you can do some very common tasks using std::string that will be really difficult in c. and much of programming is dealing with strings. speaking as a c and c++ trainer here.
- cozzyd 4y agoThe lazy way to do things with strings in C is almost always asprintf
- bitwize 4y agoMy experience is you can get to where you think you know C in a few days. But it may take decades to become aware of all its footguns, and much more time to learn how to program C in a way that avoids them -- if that can be done by humans at all. (Maybe our new AI overlords will figure it out.) Nuke the site from orbit. It's the only way to be sure. Deprecate C for all greenfield development, and launch a big-science push to rewrite all the extant load-bearing C code in something else with safety guarantees (Rust=good, SPARK=better). If null pointers were a billion dollar mistake, then letting C become ubiquitous was a mistake that runs in the trillions.
- elteto 4y agoIf this was even remotely true we wouldn’t be living in a world full of kernel exploits and broken software, with a lot of it written in C. Writing C code is hard.
- WalterBright 4y ago> Writing C code is hard I found it very easy. I was writing production C code in a few days. (Of course, I was an experienced asm programmer before that, and C was a natural.) I write code very differently today. But that's not learning C, it's learning technique.