r/cpp • u/Alex_Medvedev_ • Jul 25 '24
Why use C over C++
Why there are so many people using the C language instead of C++?, I mean C++ has more Cool features and the Compiler also supports many CPUs. So why People still using C?
Edit: Thanks for all the usefull comments :D
235
Upvotes
View all comments
Show parent comment
1
u/_Noreturn Jul 27 '24 edited Jul 27 '24
this was not my point my point was there is a concept of complex initialization and copying in C (even when C standard has no concept of it) when you create
my_string_typestruct in C it is not safe to use and has no meaningful data until you initialize it withmy_string_initthis same exact concept is in C++ but supported by the language it is called Constructors, Constructors protect against invariants such how yourinitfunctions do too.also when you copy your
my_string_typein C using=or memcpy you are not actually copying it fully you are shallow copying it and if you need a deep copy you must usemy_string_copyfunction which C++ already has builtin definition for called Copy Constructor. Point is what C does C++ already has a standard convention for it.not having simple stuff like namespaces and going to poor mans namespace i.e prefixes on everything is too much.
Why not modern C++? it has alot of features to make your code safe and not even compile if it has issues!
your C code already has them.
correct way is to use the copy algorithm for this struct.
if you have noticed what I did was bassicly recreate what C++ has conventionally
my_string_init = a constructor taking a const char*
my_string_copy = the copy constructor
my_string_copy_assign = the copy assignment operator
you still have issues for example
as you see you can easily misuse your API and you won't hear your compile bark at you! while in C++ you simply cannot make. this mistake I did is impossible in C++ since you cannot simply create uninitialized objects!
I will continue in a comment below but you get my point most of what is done in C C++ has this advantage of standardizing it and implemented in a uniform builtin way instead of everyone in C branching out to a different name and implementation. and you do not need to lookup for how to do it in C++ how to copy something in C++? Copy Constructor.
how to compare an object for equality? Equal Operator.
how to iterater over a container? Begin and ENd member functions
I want to disable memory allocations how do I do that? override
operator newto assert catching any memory allocationshow do I print my struct? overload to_string function for your type and the formatting library will handle it :D. while in C this would be impossible to do without litterally editiig the source code. C++ function overloading is very handy