Using C runtime library functions only - c++

This is most likely a stupid question, but I cannot make heads or tails of my professor's notes, so here goes:
I have an assignment to write a function in C/C++ that takes an array and sorts all instances of 0 to the back of the array. However, I am only allowed to use the C standard runtime library, not the STL or any other templated containers. I'm not entirely sure how to use the runtime library (it's my first advanced programming class and I've only ever worked in C++ before).
Do I have to include or use a namespace for the runtime library?
Is including <iostream> for C++ breaking those rules?
How about using the C++ standard library? I know it's not the STL, but I am unsure if it counts as a "templated container".

Professors tend to get a bit sloppy here. I am almost certain that you can use the standard library for console I/O, such as iostreams or *printf.
It's almost certain that he justs want you to avoid using functions like qsort or std::sort for your assignment, as that would take away the value of learning and implementing the algorithm.
As long as you implement your assigned sort manually over an array, you should be fine.
Of course the safest bet is to double-check with your professor, but I'm pretty sure this is what he/she means.

If you include the c library function (xxxxx.h) you don't include any namespace as they import into the root namespace.
To perform the actual sort, no library functions are needed at all, although I can think of one that can be adapted (qsort).
To input and output, you will need C stdio (see stdio.h) for at least fgets and fputs; although in this case scanf and printf might be easier if you don't have to handle input typos. If you've only ever done C++ before this will be a back-to-basics moment to get simple IO working. C stdio is easy. It's also easy to make really bad mistakes in.

Related

Why isn't the C++ standard library already pre-included in any C++ source?

In C++ the standard library is wrapped in the std namespace and the programmer is not supposed to define anything inside that namespace. Of course the standard include files don't step on each other names inside the standard library (so it's never a problem to include a standard header).
Then why isn't the whole standard library included by default instead of forcing programmers to write for example #include <vector> each time? This would also speed up compilation as the compilers could start with a pre-built symbol table for all the standard headers.
Pre-including everything would also solve some portability problems: for example when you include <map> it's defined what symbols are taken into std namespace, but it's not guaranteed that other standard symbols are not loaded into it and for example you could end up (in theory) with std::vector also becoming available.
It happens sometimes that a programmer forgets to include a standard header but the program compiles anyway because of an include dependence of the specific implementation. When moving the program to another environment (or just another version of the same compiler) the same source code could however stop compiling.
From a technical point of view I can image a compiler just preloading (with mmap) an optimal perfect-hash symbol table for the standard library.
This should be faster to do than loading and doing a C++ parse of even a single standard include file and should be able to provide faster lookup for std:: names. This data would also be read-only (thus probably allowing a more compact representation and also shareable between multiple instances of the compiler).
These are however just shoulds as I never implemented this.
The only downside I see is that we C++ programmers would lose compilation coffee breaks and Stack Overflow visits :-)
EDIT
Just to clarify the main advantage I see is for the programmers that today, despite the C++ standard library being a single monolithic namespace, are required to know which sub-part (include file) contains which function/class. To add insult to injury when they make a mistake and forget an include file still the code may compile or not depending on the implementation (thus leading to non-portable programs).
Short answer is because it is not the way the C++ language is supposed to be used
There are good reasons for that:
namespace pollution - even if this could be mitigated because std namespace is supposed to be self coherent and programmer are not forced to use using namespace std;. But including the whole library with using namespace std; will certainly lead to a big mess...
force programmer to declare the modules that he wants to use to avoid inadvertently calling a wrong standard function because standard library is now huge and not all programmers know all modules
history: C++ has still strong inheritance from C where namespace do not exist and where the standard library is supposed to be used as any other library.
To go in your sense, Windows API is an example where you only have one big include (windows.h) that loads many other smaller include files. And in fact, precompiled headers allows that to be fast enough
So IMHO a new language deriving from C++ could decide to automatically declare the whole standard library. A new major release could also do it, but it could break code intensively using using namespace directive and having custom implementations using same names as some standard modules.
But all common languages that I know (C#, Python, Java, Ruby) require the programmer to declare the parts of the standard library that he wants to use, so I suppose that systematically making available every piece of the standard library is still more awkward than really useful for the programmer, at least until someone find how to declare the parts that should not be loaded - that's why I spoke of a new derivative from C++
Most of the C++ standard libraries are template based which means that the code they'll generate will depend ultimately in how you use them. In other words, there is very little that could be compiled before instantiate a template like std::vector<MyType> m_collection;.
Also, C++ is probably the slowest language to compile and there is a lot parsing work that compilers have to do when you #include a header file that also includes other headers.
Well, first thing first, C++ tries to adhere to "you only pay for what you use".
The standard-library is sometimes not part of what you use at all, or even of what you could use if you wanted.
Also, you can replace it if there's a reason to do so: See libstdc++ and libc++.
That means just including it all without question isn't actually such a bright idea.
Anyway, the committee are slowly plugging away at creating a module-system (It takes lots of time, hopefully it will work for C++1z: C++ Modules - why were they removed from C++0x? Will they be back later on?), and when that's done most downsides to including more of the standard-library than strictly neccessary should disappear, and the individual modules should more cleanly exclude symbols they need not contain.
Also, as those modules are pre-parsed, they should give the compilation-speed improvement you want.
You offer two advantages of your scheme:
Compile-time performance. But nothing in the standard prevents an implementation from doing what you suggest[*] with a very slight modification: that the pre-compiled table is only mapped in when the translation unit includes at least one standard header. From the POV of the standard, it's unnecessary to impose potential implementation burden over a QoI issue.
Convenience to programmers: under your scheme we wouldn't have to specify which headers we need. We do this in order to support C++ implementations that have chosen not to implement your idea of making the standard headers monolithic (which currently is all of them), and so from the POV of the C++ standard it's a matter of "supporting existing practice and implementation freedom at a cost to programmers considered acceptable". Which is kind of the slogan of C++, isn't it?
Since no C++ implementation (that I know of) actually does this, my suspicion is that in point of fact it does not grant the performance improvement you think it does. Microsoft provides precompiled headers (via stdafx.h) for exactly this performance reason, and yet it still doesn't give you an option for "all the standard libraries", instead it requires you to say what you want in. It would be dead easy for this or any other implementation to provide an implementation-specific header defined to have the same effect as including all standard headers. This suggests to me that at least in Microsoft's opinion there would be no great overall benefit to providing that.
If implementations were to start providing monolithic standard libraries with a demonstrable compile-time performance improvement, then we'd discuss whether or not it's a good idea for the C++ standard to continue permitting implementations that don't. As things stand, it has to.
[*] Except perhaps for the fact that <cassert> is defined to have different behaviour according to the definition of NDEBUG at the point it's included. But I think implementations could just preprocess the user's code as normal, and then map in one of two different tables according to whether it's defined.
I think the answer comes down to C++'s philosophy of not making you pay for what you don't use. It also gives you more flexibility: you aren't forced to use parts of the standard library if you don't need them. And then there's the fact that some platforms might not support things like throwing exceptions or dynamically allocating memory (like the processors used in the Arduino, for example). And there's one other thing you said that is incorrect. As long as it's not a template class, you are allowed to add swap operators to the std namespace for your own classes.
First of all, I am afraid that having a prelude is a bit late to the game. Or rather, seeing as preludes are not easily extensible, we have to content ourselves with a very thin one (built-in types...).
As an example, let's say that I have a C++03 program:
#include <boost/unordered_map.hpp>
using namespace std;
using boost::unordered_map;
static unordered_map<int, string> const Symbols = ...;
It all works fine, but suddenly when I migrate to C++11:
error: ambiguous symbol "unordered_map", do you mean:
- std::unordered_map
- boost::unordered_map
Congratulations, you have invented the least backward compatible scheme for growing the standard library (just kidding, whoever uses using namespace std; is to blame...).
Alright, let's not pre-include them, but still bundle the perfect hash table anyway. The performance gain would be worth it, right?
Well, I seriously doubt it. First of all because the Standard Library is tiny compared to most other header files that you include (hint: compare it to Boost). Therefore the performance gain would be... smallish.
Oh, not all programs are big; but the small ones compile fast already (by virtue of being small) and the big ones include much more code than the Standard Library headers so you won't get much mileage out of it.
Note: and yes, I did benchmark the file look-up in a project with "only" a hundred -I directives; the conclusion was that pre-computing the "include path" to "file location" map and feeding it to gcc resulted in a 30% speed-up (after using ccache already). Generating it and keeping it up-to-date was complicated, so we never used it...
But could we at least include a provision that the compiler could do it in the Standard?
As far as I know, it is already included. I cannot remember if there is a specific blurb about it, but the Standard Library is really part of the "implementation" so resolving #include <vector> to an internal hash-map would fall under the as-if rule anyway.
But they could do it, still!
And lose any flexibility. For example Clang can use either the libstdc++ or the libc++ on Linux, and I believe it to be compatible with the Dirkumware's derivative that ships with VC++ (or if not completely, at least greatly).
This is another point of customization: if the Standard library does not fit your needs, or your platforms, by virtue of being mostly treated like any other library you can replace part of most of it with relative ease.
But! But!
#include <stdafx.h>
If you work on Windows, you will recognize it. This is called a pre-compiled header. It must be included first (or all benefits are lost) and in exchange instead of parsing files you are pulling in an efficient binary representation of those parsed files (ie, a serialized AST version, possibly with some type resolution already performed) which saves off maybe 30% to 50% of the work. Yep, this is close to your proposal; this is Computer Science for you, there's always someone else who thought about it first...
Clang and gcc have a similar mechanism; though from what I've heard it can be so painful to use that people prefer the more transparent ccache in practice.
And all of these will come to naught with modules.
This is the true solution to this pre-processing/parsing/type-resolving madness. Because modules are truly isolated (ie, unlike headers, not subject to inclusion order), an efficient binary representation (like pre-compiled headers) can be pre-computed for each and every module you depend on.
This not only means the Standard Library, but all libraries.
Your solution, more flexible, and dressed to the nines!
One could use an alternative implementation of the C++ Standard Library to the one shipped with the compiler. Or wrap headers with one's definitions, to add, enable or disable features (see GNU wrapper headers). Plain text headers and the C inclusion model are a more powerful and flexible mechanism than a binary black box.

Is there anything special I need to do to use C code in my C++ program?

Note: I am using g++ version 4.3.4 to compile my C++ code.
So far, whenever I've wanted to use C style language elements in my code it seems that I can just include the C stuff mixed in and alongside my C++.
I know C++ is mostly backwards compatible with C... so I guess my questions are these:
What parts of C are not forwards compatible with C++?
Will professional programmers laugh at me if I continue to naively stick C stuff into my C++ code?
What is the proper way to have C and C++ code in the same .cpp file?
Can I continue to use g++ to compile my hybrid code?
For this question, I am mostly concerned with a solution that deals with a single .cpp file and a single g++ command to compile it. I don't really care about linking stuff at this point.
Picking out a couple of questions:
"What is the proper way to have C and C++ code in the same .cpp file?"
"Can I continue to use g++ to compile my hybrid code?"
If you want to mix C-style C++ in the same file as regular C++, just go ahead and do it. You can trust the compiler to pick up any issues - they will be minimal and not affect the structure. By the sound of it, you are not interested in getting C-linkage for its own sake, so even if the C-Code is in its own file, compile it as C++. As a matter of fact this is often done as a way of migrating from C to C++.
If you take this approach, your code is not truly hybrid C/C++. It is C++ with some of the code using C-style procedural idioms. C++ is fully intended to support this.
"Will professional programmers laugh at me if I continue to naively stick C stuff into my C++ code?"
It depends where you are using it and why. Well structured C code is good code. Sometimes C+ is much better than C at particular problems. Think hard before using C-style dynamic memory management. You will deserved to be laughed at if you use raw malloc()/free() and get it wrong.
I suggest that if you embark on this approach, you might later take the time to look back and consider whether or not you would have been better to use C++ idioms instread of procedural C.
A big gotcha with linking C and C++ code is that the C++ compiler needs to know that it is linking against functions that use the C calling conventions instead of the C++ calling conventions. To that end, you often have to wrap your C header files in something like this:
#ifdef __cplusplus
extern "C" {
#endif
... C function declarations here ...
#ifdef __cplusplus
}
#endif
For lots of details, see the C++ FAQ.
C++ is almost a superset of C. Therefore, pretty much any feature you can use in C is valid in C++ (but not the other way around).
People might laugh at you for coding some stuff like you would in C, but ignore them. I don't think it's naive, but that may make me naive. I can't tell.
There is no [real] way to seperate C and C++ code in the same file. It just goes with each other, because when you compile it as C++, it's not C any more. So "C alongside C++" is not really the way to think about it.
The only difference between thing in C that would keep code from compiling as C++ that I am aware of (besides C++ having more keywords) is the issue with void*s. In C, they will implicitly cast to any pointer type, but in C++, you have to have an explicit cast to cast them to another pointer type. There might be others, but I don't know them.
Oh, also, C++ doesn't support "default int". I don't know if it's still valid C these days, but if you leave off the type of a variable or the return type of a function, the compiler would just use int. C++ doesn't do that.
Most good C practices make for fine compiling C++. A couple of extra pointer casts and renamed identifiers will make for legal C++.
In style, however, C-style code is considered to be horrendous C++. The fact that you can write C-style code in C++ should be used if and only if you can't afford to write it in C++ to begin with- i.e., if it's legacy code.
Will professional programmers laugh at me if I continue to naively
stick C stuff into my C++ code?
Basically, yes. C-style coding is known in C++ as "horrendously unsafe", just to begin with. That kind of code is written only by people who don't genuinely know how to use C++. By that, I don't mean doing very low-level stuff like bit twiddling or binary re-interpretation, but things like pointer casting or manual resource management, and that will get you laughed at.
This is too broad a question; you should break it up into several. There's a way to link together C and C++ object files; C++ is backward compatible with C, and you can use C++ compiler to compile C code.
But, consider this code:
int main(void)
{
int class = 0;
int private = 1;
return private-class;
}
It's valid C code, and obviously won't compile on any C++ compiler if compiled as C++ code. Just an example.
Well, the obvious key difference is that C++ is object-oriented by design and C is not. That said, you shouldn't have any horrific show-stopping issues compiling C code with g++ unless you run into one of the nasty gotchas that are floating around. You can find a lot of good references for them, and I admit that my answer is far from exhaustive.
It's true that you cannot implicitly cast from void* in C++; it won't compile, whereas you'll see it fairly often in C.
You also have to explicitly declare functions in C++ before you use them, where you don't necessarily have to in C. (It's good form to do so, but not all C programmers do.)
http://www.cprogramming.com/tutorial/c-vs-c++.html Now that I'm out of things off the top of my head, this is a good little reference; I use it frequently.

Is it bad practice to use C features in C++?

For example printf instead of cout, scanf instead of cin, using #define macros, etc?
I wouldn't say bad as it will depend on the personal choice. My policy is when there is a type-safe alternatives is available in C++, use them as it will reduce the errors in the code.
It depends on which features. Using define macros in C++ is strongly frowned upon, and for a good reason. You can almost always replace a use of a define macro with something more maintainable and safe in C++ (templates, inline functions, etc.)
Streams, on the other hand, are rightly judged by some people to be very slow and I've seen a lot of valid and high-quality C++ code using C's FILE* with its host of functions instead.
And another thing: with all due respect to the plethora of stream formatting possibilities, for stuff like simple debug printouts, IMHO you just can't beat the succinctness of printf and its format string.
You should definitely use printf in place of cout. The latter does let you make most or all of the formatting controls printf allows, but it does so in a stateful way. I.e. the current formatting mode is stored as part of the (global) object. This means bad code can leave cout in a state where subsequent output gets misformatted unless you reset all the formatting every time you use it. It also wreaks havoc with threaded usage.
I would say the only ones that are truly harmful to mix are the pairings between malloc/free and new/delete.
Otherwise it's really a style thing...and while the C is compatible with the C++, why would you want to mix the two languages when C++ has everything you need without falling back?
There are better solutions for most cases, but not all.
For example, people quite often use memcpy. I would almost never do that (except in really low-level code). I always use std::copy, even on pointers.
The same counts for the input/output routines. But it’s true that sometimes, C-style printf is substantially easier to use than cout (especially in logging). If Boost.Format isn’t an option then sure, use C.
#define is a different beast entirely. It’s not really a C-only feature, and there are many legitimate uses for it in C++. (But many more that aren’t.)
Of course you’d never use it to define constants (that’s what const is for), nor to declare inline functions (use inline and templates!).
On the other hand, it is often useful to generate debugging assertions and generally as a code generation tool. For example, I’m unit-testing class templates and without extensive use of macros, this would be a real pain in the *ss. Using macros here isn’t nice but it saves literally thousands of lines of code.
For allocations, I would avoid using malloc/free altogether and just stick to new/delete.
Not really, printf() is quite faster than cout, and the c++ iostream library is quite large. It depends on the user preference or the program itself (is it needed? etc). Also, scanf() is not suitable to use anymore, I prefer fgets().
What can be used or not only depends on the compiler that will be used. Since you are programming in c++, in my opinion, to maximize compatibility it is better to use what c++ provides instead of c functions unless you do not have any other choices.
Coming from a slightly different angle, I'd say it's bad to use scanf in C, never mind C++. User input is just far to variable to be parsed reliably with scanf.
I'd just post a comment to another reply, but since I can't... C's printf() is better than C++'s iostream because of internationalization. Want to translate a string and put the embedded number in a different place? Can't do it with an ostream. printf()'s format specification is a whole little language unto itself, interpreted at runtime.

Call C/C++ code from a Fortran 77 code

I'm trying to make a Fortran 77 wrapper for C++ code. I have not found information about it.
The idea is to use from functions from a lib that is written in C++ in a Fortran 77 progran.
Does anyone know how to do it?
Thanks!
Lawrence Livermore National Laboratory developed a tool called Babel for integrating software written in multiple languages into a single, cohesive application. If your needs are simple you can probably just put C wrapper on your C++ code and call that from Fortran. However, if your needs are more advanced, it might be worth giving Babel a look.
Calling Fortran from C is easy, C from Fortran potentially tricky, C++ from Fortran may potentially become ... challenging.
I have some notes elsewhere. Those are quite old, but nothing changes very rapidly in this sort of area, so there may still be some useful pointers there.
Unfortunately, there's no really standard way of doing this, and different compilers may do it slightly different ways. Having said that, it's only when passing strings that you're likely to run into major headaches. The resource above points to a library called CNF which aims to help here, mostly by providing C macros to sugar the bookkeeping.
The short version, however is this:
Floats and integers are generally easy -- an integer is an integer, more or less.
Strings are hard (because Fortrans quite often store these as structures, and very rarely as C-style null-terminated arrays).
C is call-by-value, Fortran call-by-reference, which means that Fortran functions are always pointer-to-value, from C's point of view.
You have to care about how your compiler generates symbols: compilers often turn C/Fortran symbol foo into _foo or foo_ or some other variant (see the compiler docs).
C tends not to have much of a runtime, C++ and Fortran do, and so you have to remember to link that in somehow, at link time.
That's the majority of what you need to know. The rest is annoying detail, and making friends with your compiler and linker docs. You'll end up knowing more about linkers than you probably wanted to.

tempnam equivalent in C++

I need to generate random names which I'll be using to create temporary files in a directory. Currently I am using C standard function tempnam() for this. My code is in C++ and would like to use C++ equivalent for doing the same task. The code needs to work on Solaris as well as on Windows.
Is anyone aware of such thing in C++? Any pointer on this would be highly appreciated.
Try std::tempnam in the cstdio header. ;)
The C standard library is still available in C++ code. For convenience, they provide C++ wrappers (in headers with the 'c' prefix, and no extension), and available in the std namespace.
You can also use the plain C version (stdio.h and tempnam in the global namespace, but you did ask for the C++ version ;))
The C++ standard library only provides new functions when there's actually room for improvement. It has a string class, because a string class is an improvement over char pointers as C has. It has a vector class, because, well, it's useful.
For something like tempnam, what would C++ be able to bring to the party, that we didn't already have from C? So they didn't do anything about it, other than making the old version available.
I know this doesn't answer your question but as a side note, according to the man page:
Although tempnam(3) generates names
that are difficult to guess, it is
nevertheless possible that between the
time that tempnam(3) returns a
pathname, and the time that the
program opens it, another program
might create that pathname using
open(2), or create it as a symbolic
link. This can lead to security
holes. To avoid such possibilities,
use the open(2) O_EXCL flag to open
the pathname. Or better yet, use
mkstemp(3) or tmpfile(3).
Why not just using the same function you are currently using in C? C++ is backward compatible with C.
What's wrong with tempnam()? You can use regular libc function right? tempnam is in stdio.h, which you're likely already including.
#include <cstdio>
using std::tmpnam;
using std::tmpfile;
You should also check this previous question on StackOverflow and avoid race conditions on creating the files using mkstemp, so I would recommend using std::tmpfile