but neither language (and they are very different) has standardised library/package tools.
but neither language (and they are very different) has standardised library/package tools.
C++ is a much more complex language than C. The things you need to worry about in C are far fewer than in C++.
perhaps i will start it up again, now it is just me, and not exactly happy, but not depressed.
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.
#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.)compare with using std::string and std::getline - easy to use and battle-hardened.
What would the equivalent code look like in C++, handling EOF and OOM conditions appropriately?
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
}I also looked up whether the cast from int to char is safe. Seems that it is not, but probably fine in practice https://stackoverflow.com/questions/19250521/best-way-to-por...
Of course all bets are off when someone tries to reverse emoji soup with this, but I am not knowledgeable enough about this topic to claim whether a general solution is even possible.
The correct way to reverse a Unicode string is to blit it back to front.
Addendum: a real C programmer helped me write (i.e., wrote most of) the following program:
#include <skalibs/skalibs.h>
int main() {
stralloc sa = STRALLOC_ZERO;
slurp(&sa, 0);
stralloc_reverse(&sa);
if (allwrite(1, sa.s, sa.len) < sa.len) {
strerror_diefusys(1, "output everything");
}
}
In the event of an allocation failure, this program will output nothing; other than that, it's the same as my C program above. Perhaps the problem isn't C, but its standard library?That's certainly at least a factor. In Rust, the "reverse a string byte by byte" bit could look like:
let reversed_string = String::from_utf8(some_string.bytes().rev().collect::<Vec<u8>>())?;
This is just what I thought of first. Peeking at the standard library examples, this one is fun: unsafe {
let vec = some_string.as_mut_vec();
vec.reverse();
}
This is unsafe because you may create invalid utf8, but we've already established that's not something we care about, so...But yeah stuff like this isn't impossible in C, though you'd not have method call syntax, of course. Rust's libraries are just richer here.
#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.
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.
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.
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.
*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.
It is certainly true that the C++ standard library provides more functionality out of the box.
string a = string("test"); string b = string(" this"); string n = string_concat(a, b); ...
Having things clean themselves up when going out of scope is very convenient, and means that the early return code style that I favour is much easier to implement.
Sure, you have to do more for yourself in C, as it isn't as powerful as C++.
C++ is the only language I've worked with where you have to tell people which bits of the language they can use!
The C++ language spec is just vast. There are many footguns when doing apparently safe things. Different code bases use different subsets of the language. It is immensely powerful.
C, by contrast, is just a much simpler language than C++. I'm not entirely sure what you are disagreeing with.
speaking as a c and c++ trainer here.
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.
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.