C++ Streams vs. C-style IO? - c++

I was coding some C++ for a small hobby project when I noticed that I'm using C-style operations to access IO (printf, fopen, etc.).
Is it considered "bad practice" to involve C functions in C++ projects? What are the advantages of using streams over C-style IO access?

This is an heated topic.
Some people prefer to use the C++ IO since they are type-safe (you can't have divergence between the type of the object and the type specified in the format string), and flow more naturally with the rest of the C++ way of coding.
However, there is also arguments for C IO functions (my personal favorites). Some of them are:
They integrate more easily with localisation, as the whole string to localise is not broken up in smaller strings, and with some implementation the localizer can reorder the order of the inserted value, move them in the string, ...
You can directly see the format of the text that will be written (this can be really hard with stream operators).
As there is no inlining, and only one instance of the printf function, the generated code is smaller (this can be important in embedded environment).
Faster than C++ function in some implementation.
Personally, I wouldn't consider it bad practice to use C stream in C++ code. Some organisations even recommend to use them over C++ stream. What I would consider bad style is to use both in the same project. Consistency is the key here I think.
As other have noted, in a relatively large project, you would probably not use them directly, but you would use a set of wrapper function (or classes), that would best fit your coding standard, and your needs (localisation, type safety, ...). You can use one or the other IO interface to implement this higher level interface, but you'll probably only use one.
Edit: adding some information about the advantage of printf formatting function family relating to the localisation. Please note that those information are only valid for some implementation.
You can use %m$ instead of % to reference parameter by index instead of referencing them sequentially. This can be used to reorder values in the formatted string. The following program will write Hello World! on the standard output.
#include <stdio.h>
int main() {
printf("%2$s %1$s\n", "World!", "Hello");
return 0;
}
Consider translating this C++ code:
if (nb_files_deleted == 1)
stream << "One file ";
else
stream << nb_file_deleted << " files ";
stream << removed from directory \"" << directory << "\"\n";
This can be really hard. With printf (and a library like gettext to handle the localization), the code is not mixed with the string. We can thus pass the string to the localization team, and won't have to update the code if there are special case in some language (in some language, if count of object is 0, you use a plural form, in other language, there are three forms one for singular, one when there is two object and a plural form, ...).
printf (ngettext ("One file removed from directory \"%2$s\"",
"%1$d files removed from directory \"%2$s\"",
n),
n, dir);

printf and friends are hideously unsafe compared to <iostream>, and cannot be extended, plus of course fopen and friends have no RAII, which means that unless you've proved with a profiler that you definitely need the performance difference (that you've proved exists on your platform and in your code), you'd have to be an idiot to printf.
Edit: Localization is an interesting thing that I hadn't considered. I've never localized any code and cannot comment on the relative localizational ability of printf and <iostream>

Nothing can be considered bad practice if it has a definite purpose. I mean, if IO is the bottleneck of the program, then yes, C-style IO works faster than C++ IO. But if it is not, I would go with C++ stream approach. Cuz it's cuter :)

For a small hobby project I would probably go with the more type-safe C++ io streams.
Funny enough, I've never seen a non-trivial real-life project that uses either of them. In all cases we used some abstractions built on top of the native OS API for IO.

Advantages
Type safety: the argument types of C++ streaming operations are checked at compile time, while printf arguments are passed through ... causing undefined behaviour if they do not match the formatting.
Resource management: C++ stream objects have destructors to close file handles, free buffers, and what have you. C streams require you to remember to call fclose.
Disadvantages
Performance: this depends on the implementation, of course, but I've found formatting with C++ streams to be considerably slower than the equivalent printf formatting.

IMHO, a real C++ programmer tries to do things in idiomatic C++ way; the C converted programmer tries to cling on old ways of doing things. It has to do with readability and consistency.

For one, you don't have to convert C++ objects (notably strings) to C-compatible forms first.

Is it considered "bad practice" to involve C functions in C++ projects?
Usually, the file IO code should be encapsulated in a class or function implementation. I wouldn't consider any choices you make in the encapsulated implementations to be "bad practice", I reserve that term for what affects the user of your library or code (i.e. the interface). If you are exposing your file IO mechanism in the interface, then, IMO, it's bad practice whether you use IO stream or C-style IO functions.
I would rather say that C-style IO functions are (probably always) the worse choice.
What are the advantages of using streams over C-style IO access?
First, they integrate better with standard C++ constructs such as std::string. They integrate fairly well with STL <algorithms>. And they allow you to create encapsulated custom read/write operators (<< and >>) such that your custom classes almost look like primitive types when it comes to doing IO operations.
Finally, IO streams in C++ can use exception mechanism to report errors in the stream or read/write operations. These make the file IO code much nicer by avoid the terrible look of error-code mechanisms (sequence of if-statements and ugly while-loops, that check the error code after each operation).

As a general rule, you should prefer C++ operators, they're:
-- Type safe. You don't risk passing a double where the format
calls for an int.
-- Extensible. You can write your own inserters and
extracters, and use them.
-- Extensible. You can define your own manipulators (with
application specific logical meaning), and use them. If you
want to change the format of all of the WidgitNumber
(internally, an int) in your output, you change the
manipulator; you don't have to find all of the format
statements where %d is a WidgitNumber.
-- Extensible. You can write your own sinks and sources, and
these can forward to other sinks and sources, filtering or
expanding the input or output as desired.
(FWIW: I don't think I've ever written an application which
didn't use custom >> and << operators, custom manipulators, and
custom streambuf's.)

Is it considered "bad practice" to involve C functions in C++ projects?
No. C functions are often used in C++ projects. Regarding the streams, Google C++ Style Guide, for example, recommends using them only in limited cases such as "ad-hoc, local, human-readable, and targeted at other developers rather than end-users".
What are the advantages of using streams over C-style IO access?
The main advantages are type safety and extensibility. However C++ streams have serious flaws, see the answers to this question such as problems with localization, poor error reporting, code bloat and performance issues in some implementations.

Related

C vs C++ file handling

I have been working in C and C++ and when it comes to file handling I get confused. Let me state the things I know.
In C, we use functions:
fopen, fclose, fwrite, fread, ftell, fseek, fprintf, fscanf, feof, fileno, fgets, fputs, fgetc, fputc.
FILE *fp for file pointer.
Modes like r, w, a
I know when to use these functions (Hope I didn't miss anything important).
In C++, we use functions / operators:
fstream f
f.open, f.close, f>>, f<<, f.seekg, f.seekp, f.tellg, f.tellp, f.read, f.write, f.eof.
Modes like ios::in, ios::out, ios::bin , etc...
So is it possible (recommended) to use C compatible file operations in C++?
Which is more widely used and why?
Is there anything other than these that I should be aware of?
Sometimes there's existing code expecting one or the other that you need to interact with, which can affect your choice, but in general the C++ versions wouldn't have been introduced if there weren't issues with the C versions that they could fix. Improvements include:
RAII semantics, which means e.g. fstreams close the files they manage when they leave scope
modal ability to throw exceptions when errors occur, which can make for cleaner code focused on the typical/successful processing (see http://en.cppreference.com/w/cpp/io/basic_ios/exceptions for API function and example)
type safety, such that how input and output is performed is implicitly selected using the variable type involved
C-style I/O has potential for crashes: e.g. int my_int = 32; printf("%s", my_int);, where %s tells printf to expect a pointer to an ASCIIZ character buffer but my_int appears instead; firstly, the argument passing convention may mean ints are passed differently to const char*s, secondly sizeof int may not equal sizeof const char*, and finally, even if printf extracts 32 as a const char* at best it will just print random garbage from memory address 32 onwards until it coincidentally hits a NUL character - far more likely the process will lack permissions to read some of that memory and the program will crash. Modern C compilers can sometimes validate the format string against the provided arguments, reducing this risk.
extensibility for user-defined types (i.e. you can teach streams how to handle your own classes)
support for dynamically sizing receiving strings based on the actual input, whereas the C functions tend to need hard-coded maximum buffer sizes and loops in user code to assemble arbitrary sized input
Streams are also sometimes criticised for:
verbosity of formatting, particularly "io manipulators" setting width, precision, base, padding, compared to the printf-style format strings
a sometimes confusing mix of manipulators that persist their settings across multiple I/O operations and others that are reset after each operation
lack of convenience class for RAII pushing/saving and later popping/restoring the manipulator state
being slow, as Ben Voigt comments and documents here
The performance differences between printf()/fwrite style I/O and C++ IO streams formatting are very much implementation dependent.
Some implementations (visual C++ for instance), build their IO streams on top of FILE * objects and this tends to increase the run-time complexity of their implementation. Note, however, that there was no particular constraint to implement the library in this fashion.
In my own opinion, the benefits of C++ I/O are as follows:
Type safety.
Flexibility of implementation. Code can be written to do specific formatting or input to or from a generic ostream or istream object. The application can then invoke this code with any kind of derived stream object. If the code that I have written and tested against a file now needs to be applied to a socket, a serial port, or some other kind of internal stream, you can create a stream implementation specific to that kind of I/O. Extending the C style I/O in this fashion is not even close to possible.
Flexibility in locale settings: the C approach of using a single global locale is, in my opinion, seriously flawed. I have experienced cases where I invoked library code (a DLL) that changed the global locale settings underneath my code and completely messed up my output. A C++ stream allows you to imbue() any locale to a stream object.
An interesting critical comparison can be found here.
C++ FQA io
Not exactly polite, but makes to think...
Disclaimer
The C++ FQA (that is a critical response to the C++ FAQ) is often considered by the C++ community a "stupid joke issued by a silly guy the even don't understand what C++ is or wants to be"(cit. from the FQA itself).
These kind of argumentation are often used to flame (or escape from) religion battles between C++ believers, Others languages believers or language atheists each in his own humble opinion convinced to be in something superior to the other.
I'm not interested in such battles, I just like to stimulate critical reasoning about the pros and cons argumentation. The C++ FQA -in this sens- has the advantage to place both the FQA and the FAQ one over the other, allowing an immediate comparison. And that the only reason why I referenced it.
Following TonyD comments, below (tanks for them, I makes me clear my intention need a clarification...), it must be noted that the OP is not just discussing the << and >> (I just talk about them in my comments just for brevity) but the entire function-set that makes up the I/O model of C and C++.
With this idea in mind, think also to other "imperative" languages (Java, Python, D ...) and you'll see they are all more conformant to the C model than C++. Sometimes making it even type safe (what the C model is not, and that's its major drawback).
What my point is all about
At the time C++ came along as mainstream (1996 or so) the <iostream.h> library (note the ".h": pre-ISO) was in a language where templates where not yet fully available, and, essentially, no type-safe support for varadic functions (we have to wait until C++11 to get them), but with type-safe overloaded functions.
The idea of oveloading << retuning it's first parameter over and over is -in fact- a way to chain a variable set of arguments using only a binary function, that can be overload in a type-safe manner. That idea extends to whatever "state management function" (like width() or precision()) through manipulators (like setw) appear as a natural consequence. This points -despite of what you may thing to the FQA author- are real facts. And is also a matter of fact that FQA is the only site I found that talks about it.
That said, years later, when the D language was designed starting offering varadic templates, the writef function was added in the D standard library providing a printf-like syntax, but also being perfectly type-safe. (see here)
Nowadays C++11 also have varadic templates ... so the same approach can be putted in place just in the same way.
Moral of the story
Both C++ and C io models appear "outdated" respect to a modern programming style.
C retain speed, C++ type safety and a "more flexible abstraction for localization" (but I wonder how many C++ programmers are in the world that are aware of locales and facets...) at a runtime-cost (jut track with a debugger the << of a number, going through stream, buffer locale and facet ... and all the related virtual functions!).
The C model, is also easily extensible to parametric messages (the one the order of the parameters depends on the localization of the text they are in) with format strings like
#1%d #2%i allowing scrpting like "text #2%i text #1%d ..."
The C++ model has no concept of "format string": the parameter order is fixed and itermixed with the text.
But C++11 varadic templates can be used to provide a support that:
can offer both compile-time and run-time locale selection
can offer both compile-time and run-time parametric order
can offer compile-time parameter type safety
... all using a simple format string methodology.
Is it time to standardize a new C++ i/o model ?

C-like procedures in C++?

Does the C++ correct programming style demand writing all your code with classes or are C-like procedures allowed ? If I were to give some code to someone else, would it be accepted as C++ just because it has std::vector and std::string (instead of char *) inside, or everything has to be a class?
eg:
int number = 204;
std::string result = my_procedure(number);
OR
MyClass machine;
std::string result = machine.get(number);
Are there cases where the programmer, will have to, or is allowed to have C-like procedures in some of his source code ? Did you ever had to do something like that?
In the context of this question where does the margin between C and C++ exist (if any)?
I hope my question is clear and inline with the rules.
It's certainly OK to have free functions in your code -- this is a matter of architecture, not of "++ness". For small programs it doesn't even make sense to go all-in with classes, as OO is really a tool to manage complexity. If the complexity isn't there to begin with, why bother?
Your second question, where is the line drawn, doesn't have a short answer. The obvious one is that the line is drawn in all places where the C standard differs from the one for C++. But if you are looking for a list of high-level language features that C++ has and C does not, here are some of them:
Class types and OO (of course)
The STL
Function/operator overloading
References
Templates
new/delete to manage memory
C++ is a multi-paradigm language, where OO, procedural, generic/generative and - to a lesser (but increasing with C++0x) extent functional - are among the paradigms. You should use whichever is the best fit for the problem: you want the code to be easy to get and keep right, and hard to stuff up.
The utility of classes is in packaging data (state) along with the related functions. If your wordify function doesn't need to retain any state between calls, then there's no need to use a class/object. That said, if you can predict that you will soon want to have state, then it may be useful to start with a class so that the client code doesn't need to change as much.
For example, imagine adding a parameter to the function to specify whether the output should be "first", "second" instead of "one", "two". You want the behaviour to be set once and remembered, but somewhere else in the application some other code may also use the functionality but prefer the other setting. It's a good idea to use an object to hold the state and arrange it so each object's lifetime and accessibility aligns with the code that will use it.
EDIT:
In the context of this question where does the margin between C and C++ exist (if any)?
C++ just gives you a richer set of ways to tackle your programming tasks, each with their necessary pros and cons. There are plenty of times when the best way is still the same way it would have been done in C. It would be perverse for a C++ programmer to choose a worse way simply because it was only possible in C++. Still, such choices exist at myriad levels, so it's common to have say a non-[class-]member function that takes a const std::string& parameter, combining the procedural function call with object-oriented data that's been generated by a template: it all works well together.
C++ allows a variety of programming styles, procedural code being one of them.
Which style to use depends on the problem you are trying to solve. The margin between C and C++ is are you compiling your code with a C++ compiler.
I do at times use procedural functions in my code. Sometimes it best solves the problem.
C++ code can still be valid C++ code even without classes. Classes are more of a feature, and are not required in every piece of code.
C++ is basically C with more features, so there isn't really a "margin" between the two languages.
If you read Stroustrup's Design and Evolution, you'll see that C++ was intended to support multiple programming styles. Use whichever one is most appropriate the problem (not the same as always just usnig the one you know.)
In legacy real world applications, there is often very little distinction. Some C++ code was originally C code nad then recompilied. Slowly it migrates to use C++ features to improve its quality.
In short, Yes, C++ code can be procedural. But you'll find it does differ from C code if you use C++ features where appropriate.
What is good practice needs to consider things like encapsulation, testability, and the comprehensibility of the client API.
#include <sstream>
#include <string>
#include <iostream>
using namespace std;
string wordify(int n)
{
stringstream ss;
ss << n; // put the integer into the stream
return ss.str(); // return the string
}
int main()
{
string s1 = wordify(42);
string s2 = wordify(45678);
string s3 = wordify(-99);
cout << s1 << ' ' << s2 << ' ' << s3 << '\n';
}

Why we do not use Printf and Scanf in C++? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Which I/O library do you use in your C++ code?
in C++ why we go for COUT and CIN
Because classes can overload the insertion operator <<
They cannot edit printf and add %Foo to know how to print a Foo class.
You can use them.
But the major problem is that they are not safe.
A lot of C code had problems because the format specifiers did not match the arguments and resulted in crashes etc.
// Example
char c;
scanf("%s",&c); // quite an easy mistake. Usually leads to a crash or something worse.
The C++ variants are type safe (in that the compiler guarantees that the type you are inputting into is the correct type at compile time) and the runtime does the work of actually moving the data.
A secondary reason is that it is a lot easier to define output functions in C++ (operator >> and <<) than in C (There was never a standardized way of naming streaming functions).
The third advantage is that a stream is not limited to console or file. There are several other types of stream that automatically work with the operator >> and << thus allowing you to generalize the streaming (or serialization) of objects in different circumstances.
Along with the ability to overload insertion and extraction operators for classes of your choice, cin and cout are type-safe, which scanf and printf are not -- e.g., a mismatch between the conversion format and actual type with printf is fairly common:
printf("%d\n", 1.0);
printf("%f\n", 1);
Neither of these is at all likely to produce useful output.
The old stdio functionality is in C++ for compatibility (and partially because the original C++ (cfront) was just a pre-processor for C so they were available anyway).
The newer I/O model found in C++ is a lot more flexible, allowing you to add types at will, which can be printed in a way defined by that type.
In other words, in an object oriented way.
Just like complex or rational numbers numbers (or address book entries or dictionary entries or any other non-basic type for that matter) should be self contained in a class that knows how to add, subtract or otherwise manipulate them separately from the base language, the printing of those objects should also be left to the class as well.
If you're worried about the verbosity of the C++ way, there's nothing stopping you from adding a fmt() method, returning a string, to your own data types to get around that problem, something like:
std::cout << name.fmt('left',15) // [Pax Diablo ]
<< " " << age.fmt(4) // [ 45]
<< " " << score.fmt(3,2) // [100.00]
<< std::endl;
for sizes and/or justifications.
It's more coding on your part within the class but it is an option if you're really adverse to the setfill and setw stuff.
However, since you'll almost certainly have your formatting code in a function for each type of output (if you're smart), it'll be isolated in one area. I'd just suck it up and learn the C++ way of doing things.
The C++ syntax is supposed to be easier but, frankly, I never adopted it. Besides, I do Windows programming, not console, so neither cout or printf are of much use. But sprintf and it's variations are.

Moving from C++ to C

After a few years coding in C++, I was recently offered a job coding in C, in the embedded field.
Putting aside the question of whether it's right or wrong to dismiss C++ in the embedded field, there are some features/idioms in C++ I would miss a lot. Just to name a few:
Generic, type-safe data structures (using templates).
RAII. Especially in functions with multiple return points, e.g. not having to remember to release the mutex on each return point.
Destructors in general. I.e. you write a d'tor once for MyClass, then if a MyClass instance is a member of MyOtherClass, MyOtherClass doesn't have to explicitly deinitialize the MyClass instance - its d'tor is called automatically.
Namespaces.
What are your experiences moving from C++ to C?
What C substitutes did you find for your favorite C++ features/idioms? Did you discover any C features you wish C++ had?
Working on an embedded project, I tried working in all C once, and just couldn't stand it. It was just so verbose that it made it hard to read anything. Also, I liked the optimized-for-embedded containers I had written, which had to turn into much less safe and harder to fix #define blocks.
Code that in C++ looked like:
if(uart[0]->Send(pktQueue.Top(), sizeof(Packet)))
pktQueue.Dequeue(1);
turns into:
if(UART_uchar_SendBlock(uart[0], Queue_Packet_Top(pktQueue), sizeof(Packet)))
Queue_Packet_Dequeue(pktQueue, 1);
which many people will probably say is fine but gets ridiculous if you have to do more than a couple "method" calls in a line. Two lines of C++ would turn into five of C (due to 80-char line length limits). Both would generate the same code, so it's not like the target processor cared!
One time (back in 1995), I tried writing a lot of C for a multiprocessor data-processing program. The kind where each processor has its own memory and program. The vendor-supplied compiler was a C compiler (some kind of HighC derivative), their libraries were closed source so I couldn't use GCC to build, and their APIs were designed with the mindset that your programs would primarily be the initialize/process/terminate variety, so inter-processor communication was rudimentary at best.
I got about a month in before I gave up, found a copy of cfront, and hacked it into the makefiles so I could use C++. Cfront didn't even support templates, but the C++ code was much, much clearer.
Generic, type-safe data structures (using templates).
The closest thing C has to templates is to declare a header file with a lot of code that looks like:
TYPE * Queue_##TYPE##_Top(Queue_##TYPE##* const this)
{ /* ... */ }
then pull it in with something like:
#define TYPE Packet
#include "Queue.h"
#undef TYPE
Note that this won't work for compound types (e.g. no queues of unsigned char) unless you make a typedef first.
Oh, and remember, if this code isn't actually used anywhere, then you don't even know if it's syntactically correct.
EDIT: One more thing: you'll need to manually manage instantiation of code. If your "template" code isn't all inline functions, then you'll have to put in some control to make sure that things get instantiated only once so your linker doesn't spit out a pile of "multiple instances of Foo" errors.
To do this, you'll have to put the non-inlined stuff in an "implementation" section in your header file:
#ifdef implementation_##TYPE
/* Non-inlines, "static members", global definitions, etc. go here. */
#endif
And then, in one place in all your code per template variant, you have to:
#define TYPE Packet
#define implementation_Packet
#include "Queue.h"
#undef TYPE
Also, this implementation section needs to be outside the standard #ifndef/#define/#endif litany, because you may include the template header file in another header file, but need to instantiate afterward in a .c file.
Yep, it gets ugly fast. Which is why most C programmers don't even try.
RAII.
Especially in functions with multiple return points, e.g. not having to remember to release the mutex on each return point.
Well, forget your pretty code and get used to all your return points (except the end of the function) being gotos:
TYPE * Queue_##TYPE##_Top(Queue_##TYPE##* const this)
{
TYPE * result;
Mutex_Lock(this->lock);
if(this->head == this->tail)
{
result = 0;
goto Queue_##TYPE##_Top_exit:;
}
/* Figure out `result` for real, then fall through to... */
Queue_##TYPE##_Top_exit:
Mutex_Lock(this->lock);
return result;
}
Destructors in general.
I.e. you write a d'tor once for MyClass, then if a MyClass instance is a member of MyOtherClass, MyOtherClass doesn't have to explicitly deinitialize the MyClass instance - its d'tor is called automatically.
Object construction has to be explicitly handled the same way.
Namespaces.
That's actually a simple one to fix: just tack a prefix onto every symbol. This is the primary cause of the source bloat that I talked about earlier (since classes are implicit namespaces). The C folks have been living this, well, forever, and probably won't see what the big deal is.
YMMV
I moved from C++ to C for a different reason (some sort of allergic reaction ;) and there are only a few thing that I miss and some things that I gained. If you stick to C99, if you may, there are constructs that let you program quite nicely and safely, in particular
designated initializers (eventually
combined with macros) make
initialization of simple classes as
painless as constructors
compound literals for temporary variables
for-scope variable may help you to do scope bound resource management, in particular to ensure to unlock of mutexes or free of arrays, even under preliminary function returns
__VA_ARGS__ macros can be used to have default arguments to functions and to do code unrolling
inline functions and macros that combine well to replace (sort of) overloaded functions
The difference between C and C++ is the predictability of the code's behavior.
It is a easier to predict with great accuracy what your code will do in C, in C++ it might become a bit more difficult to come up with an exact prediction.
The predictability in C gives you better control of what your code is doing, but that also means you have to do more stuff.
In C++ you can write less code to get the same thing done, but (at leas for me) I have trouble occasionally knowing how the object code is laid out in memory and it's expected behavior.
Nothing like the STL exists for C.
There are libs available which provide similar functionality, but it isn't builtin anymore.
Think that would be one of my biggest problems... Knowing with which tool I could solve the problem, but not having the tools available in the language I have to use.
In my line of work - which is embedded, by the way - I am constantly switching back & forth between C and C++.
When I'm in C, I miss from C++:
templates (including but not limited to STL containers). I use them for things like special counters, buffer pools, etc. (built up my own library of class templates & function templates that I use in different embedded projects)
very powerful standard library
destructors, which of course make RAII possible (mutexes, interrupt disable, tracing, etc.)
access specifiers, to better enforce who can use (not see) what
I use inheritance on larger projects, and C++'s built-in support for it is much cleaner & nicer than the C "hack" of embedding the base class as the first member (not to mention automatic invocation of constructors, init. lists, etc.) but the items listed above are the ones I miss the most.
Also, probably only about a third of the embedded C++ projects I work on use exceptions, so I've become accustomed to living without them, so I don't miss them too much when I move back to C.
On the flip side, when I move back to a C project with a significant number of developers, there are whole classes of C++ problems that I'm used to explaining to people which go away. Mostly problems due to the complexity of C++, and people who think they know what's going on, but they're really at the "C with classes" part of the C++ confidence curve.
Given the choice, I'd prefer using C++ on a project, but only if the team is pretty solid on the language. Also of course assuming it's not an 8K μC project where I'm effectively writing "C" anyway.
Couple of observations
Unless you plan to use your c++ compiler to build your C (which is possible if you stick to a well define subset of C++) you will soon discover things that your compiler allows in C that would be a compile error in C++.
No more cryptic template errors (yay!)
No (language supported) object oriented programming
Pretty much the same reasons I have for using C++ or a mix of C/C++ rather than pure C. I can live without namespaces but I use them all the time if the code standard allows it. The reasons is that you can write much more compact code in C++. This is very usefull for me, I write servers in C++ which tend to crash now and then. At that point it helps a lot if the code you are looking at is short and consist. For example consider the following code:
uint32_t
ScoreList::FindHighScore(
uint32_t p_PlayerId)
{
MutexLock lock(m_Lock);
uint32_t highScore = 0;
for(int i = 0; i < m_Players.Size(); i++)
{
Player& player = m_Players[i];
if(player.m_Score > highScore)
highScore = player.m_Score;
}
return highScore;
}
In C that looks like:
uint32_t
ScoreList_getHighScore(
ScoreList* p_ScoreList)
{
uint32_t highScore = 0;
Mutex_Lock(p_ScoreList->m_Lock);
for(int i = 0; i < Array_GetSize(p_ScoreList->m_Players); i++)
{
Player* player = p_ScoreList->m_Players[i];
if(player->m_Score > highScore)
highScore = player->m_Score;
}
Mutex_UnLock(p_ScoreList->m_Lock);
return highScore;
}
Not a world of difference. One more line of code, but that tends to add up. Nomally you try your best to keep it clean and lean but sometimes you have to do something more complex. And in those situations you value your line count. One more line is one more thing to look at when you try to figure out why your broadcast network suddenly stops delivering messages.
Anyway I find that C++ allows me to do more complex things in a safe fashion.
yes! i have experienced both of these languages and what i found is C++ is more friendly language. It facilitates with more features. It is better to say that C++ is superset of C language as it provide additional features like polymorphism, interitance, operator and function overloading, user defined data types which is not really supported in C. The thousand lines of code is reduce to few lines with the help of object oriented programming that's the main reason of moving from C to C++.
I think the main problem why c++ is harder to be accepted in embedded environment is because of the lack of engineers that understand how to use c++ properly.
Yes, the same reasoning can be applied to C as well, but luckily there aren't that many pitfalls in C that can shoot yourself in the foot. C++ on the other hand, you need to know when not to use certain features in c++.
All in all, I like c++. I use that on the O/S services layer, driver, management code, etc.
But if your team doesn't have enough experience with it, it's gonna be a tough challenge.
I had experience with both. When the rest of the team wasn't ready for it, it was a total disaster. On the other hand, it was good experience.
Certainly, the desire to escape complex/messy syntax is understandable. Sometimes C can appear to be the solution. However, C++ is where the industry support is, including tooling and libraries, so that is hard to work around.
C++ has so many features today including lambdas.
A good approach is to leverage C++ itself to make your code simpler. Objects are good for isolating things under the hood so that at a higher level, the code is simpler. The core guidelines recommend concrete (simple) objects, so that approach can help.
The level of complexity is under the engineer's control. If multiple inheritance (MI) is useful in a scenario and one prefers that option, then one may use MI.
Alternatively, one can define interfaces, inherit from the interface(s), and contain implementing objects (composition/aggregation) and expose the objects through the interface using inline wrappers. The inline wrappers compile down to nothing, i.e., compile down to simple use of the internal (contained) object, yet the container object appears to have that functionality as if multiple inheritance was used.
C++ also has namespaces, so one should leverage namespaces even if coding in a C-like style.
One can use the language itself to create simpler patterns and the STL is full of examples: array, vector, map, queue, string, unique_ptr,... And one can control (to a reasonable extent) how complex their code is.
So, going back to C is not the way, nor is it necessary. One may use C++ in a C-like way, or use C++ multiple inheritance, or use any option in-between.

Why use c strings in c++?

Is there any good reason to use C-strings in C++ nowadays? My textbook uses them in examples at some points, and I really feel like it would be easier just to use a std::string.
The only reasons I've had to use them is when interfacing with 3rd party libraries that use C style strings. There might also be esoteric situations where you would use C style strings for performance reasons, but more often than not, using methods on C++ strings is probably faster due to inlining and specialization, etc.
You can use the c_str() method in many cases when working with those sort of APIs, but you should be aware that the char * returned is const, and you should not modify the string via that pointer. In those sort of situations, you can still use a vector<char> instead, and at least get the benefit of easier memory management.
A couple more memory control notes:
C strings are POD types, so they can be allocated in your application's read-only data segment. If you declare and define std::string constants at namespace scope, the compiler will generate additional code that runs before main() that calls the std::string constructor for each constant. If your application has many constant strings (e.g. if you have generated C++ code that uses constant strings), C strings may be preferable in this situation.
Some implementations of std::string support a feature called SSO ("short string optimization" or "small string optimization") where the std::string class contains storage for strings up to a certain length. This increases the size of std::string but often significantly reduces the frequency of free-store allocations/deallocations, improving performance. If your implementation of std::string does not support SSO, then constructing an empty std::string on the stack will still perform a free-store allocation. If that is the case, using temporary stack-allocated C strings may be helpful for performance-critical code that uses strings. Of course, you have to be careful not to shoot yourself in the foot when you do this.
Because that's how they come from numerous API/libraries?
Let's say you have some string constants in your code, which is a pretty common need. It's better to define these as C strings than as C++ objects -- more lightweight, portable, etc. Now, if you're going to be passing these strings to various functions, it's nice if these functions accept a C string instead of requiring a C++ string object.
Of course, if the strings are mutable, then it's much more convenient to use C++ string objects.
If a function needs a constant string I still prefer to use 'const char*' (or const wchar_t*) even if the program uses std::string, CString, EString or whatever elsewhere.
There are just too many sources of strings in a large code base to be sure the caller will have the string as a std::string and 'const char*' is the lowest common denominator.
Textbooks feature old-school C strings because many basic functions still expect them as arguments, or return them. Additionally, it gives some insight into the underlying structure of the string in memory.
Memory control. I recently had to handle strings (actually blobs from a database) about 200-300 MB in size, in a massively multithreaded application. It was a situation where just-one-more copy of the string might have burst the 32bit address space. I had to know exactly how many copies of the string existed. Although I'm an STL evangelist, I used char * then because it gave me the guarantee that no extra memory or even extra copy was allocated. I knew exactly how much space it would need.
Apart from that, standard STL string processing misses out on some great C functions for string processing/parsing. Thankfully, std::string has the c_str() method for const access to the internal buffer. To use printf() you still have to use char * though (what a crazy idea of the C++ team to not include (s)printf-like functionality, one of the most useful functions EVER in C. I hope boost::format will soon be included in the STL.
If the C++ code is "deep" (close to the kernel, heavily dependent on C libraries, etc.) you may want to use C strings explicitly to avoid lots of conversions in to and out of std::string. Of, if you're interfacing with other language domains (Python, Ruby, etc.) you might do so for the same reason. Otherwise, use std::string.
Some posts mention memory concerns. That might be a good reason to shun std::string, but char* probably is not the best replacement. It's still an OO language. Your own string class is probably better than a char*. It may even be more efficient - you can apply the Small String Optimization, for instance.
In my case, I was trying to get about 1GB worth of strings out of a 2GB file, stuff them in records with about 60 fields and then sort them 7 times of different fields. My predecessors code took 25 hours with char*, my code ran in 1 hour.
1) "string constant" is a C string (const char *), converting it to const std::string& is run-time process, not necessarily simple or optimized.
2) fstream library uses c-style strings to pass file names.
My rule of thumb is to pass const std::string& if I am about to use the data as std::string anyway (say, when I store them in a vector), and const char * in other cases.
After spending far, far, too much time debugging initialization rules and every conceivable string implementation on several platforms we require static strings to be const char*.
After spending far, far, too much time debugging bad char* code and memory leaks I suggest that all non-static strings be some type of string object ... until profiling shows that you can and should do something better ;-)
Legacy code that doesn't know of std::string. Also, before C++11 opening files with std::ifstream or std::ofstream was only possible with const char* as an input to the file name.
Given the choice, there is generally no reason to choose primitive C strings (char*) over C++ strings (std::string). However, often you don't have the luxury of choice. For instance, std::fstream's constructors take C strings, for historical reasons. Also, C libraries (you guessed it!) use C strings.
In your own C++ code it is best to use std::string and extract the object's C string as needed by using the c_str() function of std::string.
It depends on the libraries you're using. For example, when working with the MFC, it's often easier to use CString when working with various parts of the Windows API. It also seems to perform better than std::string in Win32 applications.
However, std::string is part of the C++ standard, so if you want better portability, go with std::string.
For applications such as most embedded platforms where you do not have the luxury of a heap to store the strings being manipulated, and where deterministic preallocation of string buffers is required.
c strings don't carry the overhead of being a class.
c strings generally can result in faster code, as they are closer to the machine level
This is not to say, you can't write bad code with them. They can be misused, like every other construct.
There is a wealth of libary calls that demand them for historical reasons.
Learn to use c strings, and stl strings, and use each when it makes sense to do so.
STL strings are certainly far easier to use, and I don't see any reason to not use them.
If you need to interact with a library that only takes C-style strings as arguments, you can always call the c_str() method of the string class.
The usual reason to do it is that you enjoy writing buffer overflows in your string handling. Counted strings are so superior to terminated strings it's hard to see why the C designers ever used terminated strings. It was a bad decision then; it's a bad decision now.