I assume most C++ compilers are written in assembly. Which makes them different languages entirely (I could be wrong). That being said if I were going to create a cout style function for plain old C, how would I do it? cout has some very impressive features take this snippet for example:
// endl not only prints a new line but also flushes the stream
cout << "Hello World!" << endl;
Which I'm pretty sure translates to this in C:
printf("Hello World!\n");
fflush(1); //stdout = 1
Next order of business, the << operators. In C++ this would be easy (operator overloading), but I can't think of a single way to do this in C.
It may help in thinking about this to translate between the "<<" operator syntax and the "operator<<" function syntax. Your C++ example is equivalent to this bit of C++ code:
operator<< ( operator<< (cout, "Hello World!"), endl);
The first thing that you should notice here is that there is not actually a lot of cleverness in cout at all. What is clever is the operator<< function -- specifically, the version of the operator<< function that takes a stream object (which is what cout is, but many other things are too) as its first argument. Or, even more precisely, the range of operator<< functions that take a stream object as the first argument, and take a particular thing as the second argument -- there's one for each type of object that you can put into the cout stream. You can see one of the C++ tricks in that syntax, too; the operator<< functions on stream objects always return the stream object that they were given, thereby allowing chaining of this nature.
In order to put C++ code into linkers and system ABIs that expect C-like function syntax, most C++ compilers "mangle" the function names, in order to encode in them the type of arguments that they have. (Also, of course, the "<<" isn't a valid C-like function name.) So, if you looked at the generated assembly for this bit of function, you'd see that the names of the two functions were different from each other -- they'd have suffixes indicating the argument types. You could do something like that manually:
operator_lshift__stream__endl(
operator_lshift__stream__string(cout, "Hello World!"), endl);
And there you've got something that you could implement in C.
That's right, because C does not have operator overloading, you cannot change the behaviour of the << operator, it will always do a bit shift, so there is no way to write 'cout' with the precise semantics it has in C++, in C.
Out of interest, g++ (GNU C++ Compiler) is written mostly in C.
C is actually a popular implementation language for C++ compilers and standard libraries (so is C++ itself, actually -- a concept sometimes known as self-hosting or bootstrapping a language), and you can study the whole sources of a rich, complex C++ standard library (plus extensions) here (sorry, this is gcc 3 -- can't find a gcc 4 source tree that's just as easily browseable online, though of course you can easily download those sources and study them on your local machine).
Personally, I would suggest starting instead with a good book, such as this one -- the sources will be much more meaningful to you once you've got a good grasp of all the obscure nooks and crannies of C++'s iostreams (as a bonus, the book also takes you on a guided tour through locales -- hold on to your hat!-).
Related
I am attempting to build a third-party C++ code base in which there are several places where an attempt is made to print an output stream to itself. This example demonstrates an expression of the same form:
#include <iostream>
int main(void) {
std::cout << std::cout << "Say what?" << std::endl;
return 0;
}
I find that without any options, g++ 4.8.5 accepts that code with zero complaints, but g++ 8.2.1 rejects it with a good old "no match for ‘operator<<’" error.
I understand the error. What I want to know is whether there is any reason to think that it was ever anything other than an error -- was there a C++ version or a widely used C++ compiler that would do something useful with such code? Although it accepts the code, g++ 4.8.5 is not such a compiler in my book because the program it builds evaluates the first << operation simply by outputting a hexadecimal number of unclear significance.
I have considered that it might be a simple typo, maybe magnified by copy & paste. For example, perhaps the second std::cout was an accidental duplicate of the first, or perhaps it was meant to be std::endl, instead. However, in a different source file in the same code base I see the same idiom of an output stream being printed to itself applied to objects of type std::stringstream, which suggests to me that it might be intentional.
My overall objective is to decide how best to fix the code.
What might be the intention of printing a stream to itself?
It is probably unintentional, or the intention itself was a mistake.
The difference between the GCC versions is the default dialect of C++ that they use. The newer GCC defaults to c++11 or newer. The program should compile with the newer compiler as long as you use a pre-C++11 dialect.
The change in C++11 was the removal of implicit conversion from std::basic_ios to void*. The purpose of this conversion was to check for failure state of the stream: null signified a failed stream while non-null signified a valid stream which allows the pattern if(stream >> input). In C++11 the conversion was replaced with explicit conversion to bool. Since the new conversion is explicit, it won't be applied to inserting a stream into stream. This was a backwards incompatible change which was presumably considered to not be a problem since the now-incompatible ways of using the conversion (such as the example) would have had no practical uses. In fact, it is useful to get a compilation error when doing something that has no practical use.
My overall objective is to decide how best to fix the code.
Probably just remove the insertion of cout into cout. If you're concerned that the output must remain same because it might be parsed by another program, then you can output any non-zero hex number to keep the output same for the sake of compatibility.
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 ?
I am using gcc 4.2.4.
According to Schildt, "C++ The Complete Reference", 1995, user defined parameterized manipulators should be defined as:
istream &mymanip(istream &stream, type param)
{
// here my code
return stream;
}
// overload
imanip<type> mymanip(type param){
return imanip<type>(mymanip, param)
}
// usage
cin >> mymanip(param);
I believe that imanip(mymanip, param) is supposed to return an object that contains mymanip and mymanip's arguments. This should be used by an overloaded operator>> to call mymanip. However, this does not work, imanip is not declared.
I also found this version:
IMANIP(int) fld(int n){
return IMANIP(int)(fld,n);
}
which also does not work.
My questions are:
does gcc 4.2.4 follow the ANSI C++ standard on this detail or not? If it does, did the standard change since 1995 in this respect?
in order to define my own parameterized manipulators do I need to understand the iostream code and write my own overloaded imanip and operator>> functions?
regardless the answer to question 2, what is the best strategy for me to understand the iostream code? Should I read the code? How do I find out the names of compiled libraries which are part of iostream? Should I read a book?
The code you posted seems out of context. imanip looks like some template, but that template is never defined anywhere in your code.
But to be honest, I would not even consider using a 1995 book on C++ any more. In 1995 C++ was not even standardized, although there existed an "annotated reference manual". Your book is over 17 years old, which means "more than extremely outdated" when it comes to programming languages. C++ has evolved a lot since then, you should consider to buy a more recent book, perhaps take a look at http://isocpp.org/get-started to give you some examples.
To give you more specific answers to your questions:
Yes, gcc follows the standard in this regard, but your book might not, because it is pre-standard.
Manipulators are made so you do not have to reimplement the op<< and op>> again. However, depending on what your manipulators are designed to do, you might need to call some of the lower level methods provided by the stream or streambuf.
"The code" does not exist, there are several implementors of standard libraries, and they all have their own, sometimes very complicated code for etc. I would recommend to search the web for information about how those libraries work. Of course, a book is even better. Consider buying "The C++ Standard Library" by N. Josuttis. There is a recent Edition that covers the standard library "as of now and tomorrow", i.e. including the additions of the C++11 standard.
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';
}
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.