When to use printf/scanf vs cout/cin? - c++

I'm testing some snippets I found off the web using g++ from MinGW. This is the C++ compiler...why then does it correctly compile C....why do people intertwine C and C++.
The concrete question is: Is it O.K. to use both C and C++ and compile under g++. If the answer is yes, this makes my life easy as I do not have to modify the code.
Oddly enough...to get some C++ to work, particularly when passing a string to an ifstream constructor it requires a C type string...
My guess would be that because C++ depends upon C constructs at times is is O.K to write the two languages together.
However as a matter of style you should settle on cout/cin or printf/scanf.

There are a few oddities where char* is needed. You can bridge the gap by using the .c_str() method of a std::string to get one.
For the most part, the C subset of C++ is compatible. Exactly how it isn't compatible is not likely to matter for the most part:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
If you're compiling snippets of C code under a C++ compiler, be sure to change it to use the "c" lib format in your includes...for example #include <cstdio> instead of #include <stdio.h>
Is it bad practice to use a C header instead of its C++ equivalent in C++ (e.g. stdio.h instead of cstdio)?
For a fairly reasoned argument from Bjarne himself on why to avoid scanf, check out the beginning of this paper:
http://www.stroustrup.com/new_learning.pdf
There are a lot of benefits to using iostreams instead of printf as well:
'printf' vs. 'cout' in C++

The C++ language inherits much of its core functionality from C. That's because C++ was derived from C. The C++ Standard includes, by reference much of the C Standard. Therefore you can use the C++ compiler to write code using C constructs, idioms and paradigms. Doing so is often referred to as using C++ "as a better C."
The long and the short of the above is yes, you can use printf in C++ code. Doing so is explicitly allowed by the Standard.
Doing this however will often neglect many of the features that define C++. I'll leave that conversation for another question but suffice it to say that many people will tell you simply "don't do that" or "that's not C++." This sets aside the reasons why you might not want to use printf in a C++ program or indeed why you would want to. But rest assured that it is technically allowed.

Is it O.K. to use both C and C++ and compile under g++.
Yes, it is fine to mix the two languages. This is common with code that started out as C, but then got more and more C++ features added (obviously somebody changed the compiler along the way).
Generally, C code will compile and run with a C++ compiler. There are many possible exceptions, such as use of keywords like class and virtual for names of things in C code, or C's relaxed casting rules.
You will often hear people say "they are very different languages". That's because any programming question you ask probably has a different answer depending on which language you're trying to use. However, there are lots of similarities and backwards compatibility aspects as well.

If you use C++, then use C++. (cin,cout)
Why fstream takes c string puzzles me too.

Related

Can functions from the C standard library be used in C++?

Right now I'm getting familiar with C and the C standard library and I wonder if my knowledge in this area will be useful when I turn to working with C++ at a later time.
Therefore I'd like to know, whether I can use the functions provided by the C standard library in a C++ setting, and also whether and why it would make sense to actually do so.
Yes, C++ was originally designed so that any C library can be easily used in C++. Of course this is slightly less true (in particular, if a C library happens to use some C++ keyword like try or dynamic_cast, it won't work; also, if a callback coded in C++ passed to a C library is raising some exception, you are likely to have a big mess).
The standard practice to use a C header file in C++ is
extern "C" {
#include <some_c_header_file.h>
};
and most existing C header files are designed to cooperate with C++ by actually containing stuff like
#ifdef __cplusplus
extern "C" {
#endif
//// most of the header material goes here, C style
#ifdef __cplusplus
}; // end extern "C"
#endif
In practice, many C standard headers have equivalent C++ headers wrapping things like above (and also in namespace std). Eg C <stdio.h> is C++ <cstdio> -but you often should prefer genuine C++ streams (<iostream>), however printf-like routines are usually more localization friendly mixed with gettext(3).
However C and C++ are very different languages. You should code in idiomatic C++11 (using standard C++ containers, auto, closures, RAII, smart pointers, rule of five, SFINAE, exceptions, anonymous functions, ...)
Some standard C functions are not very useful in idiomatic C++. For example, you are unlikely to use directly malloc in genuine C++ (at least prefer new -which is still very low level and no more in the C++ spirit-, more likely use a lot the containers and the smart pointers without dealing manually with heap allocation). But POSIX functions (notably syscalls(2) ....) are quite useful in C++. longjmp is likely to be incompatible with C++ exceptions.
BTW, C++ has evolved a lot in this century. Don't learn C++98 but at least C++11 (there are tremendous differences between them) and perhaps C++14. Use a recent compiler (GCC or Clang/LLVM); in december 2015, that means GCC 5 at least or Clang/LLVM 3.7 at least. Don't forget to enable all warnings & debug info in the compiler (e.g. g++ -Wall -Wextra -g -std=c++11)
C++ (that means C++11 at least) is a difficult programming language, considerably more complex than C is. You'll need weeks of reading to learn some of it, and good coding style and discipline is essential (you can easily write very crappy code in C++). Start with Programming: Principles & Practice Using C++
I believe that if you only know C, reading SICP (and studying a bit of Scheme) before learning C++ is worthwhile.
The notion of undefined behavior is very important, both in C and probably even more in C++. You absolutely need to understand it (see C.Lattner's blog on it) and avoid it.
You will also learn a big lot by studying (and perhaps contributing to) some existing free software and its source code. Hence I recommend using Linux.
I'll just quote a paragraph out of the ISO/IEC N3690(c++ standard).
17.2 The C standard library
1 The C++ standard library also makes available the facilities of the C standard library, suitably adjusted to ensure static type safety.
So simply yes!
yes .you can use standard c library functions in C++
Examples
stdio.h => cstdio (printf/scanf)
math.h => cmath (sqrt)

Can we mix c and c++ code

I was reading this website
http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
which is a C++ website.But, it uses printf to display things. However, i thought in c++, we use cout to display things. Can we mix c and C++ code as they have done here.
There is no mix of C++ and C code. While you certainly can use cout in C++, you can also use printf. The vast majority of things that are legal C code are also legal C++ code. In fact, section 27.8.2 of the C++ standard requires printf to be defined if your code #include's <cstdio>.
Technically speaking, yes you can mix C and C++ code. C++ is a near super-set of C and has all of the C libraries (save for a few slight differences).
However, whether or not you should mix C and C++ is another story. Generally speaking, if you write in C++, you should stick to C++ constructs.
Yes, C and C++ are (with very few exceptions) both possible and easy to mix. One example where you may have problems is mixing printf and cout, output may not come in the order you expect.
In C++ the C-runtime is available since C++ is to a great degree compatible with C by design in order to be backwards compatible. That said, if you are programming C++ you should avoid using the C run-time as much as possible since C++ offers much more in terms of functionality and safety. e.g. vector, string
Of course you can! But make sure you're saving the code in a .cpp file. Some compilers wouldn't compile C++ code in a .c file.
C++ contains (most of) C as a subset (although this isn't a strict subset). If you #include <cstdio> you can use things such as printf, however, unless you have a really good reason, you should stick with using C++ constructs (std::vector, std::cout, new, delete, etc).
yes you can mix the 2 codes, but then the resultant code should be in C++ if you are reluctant to edit for compatibility with C. C++ is backward for most of the code
To let the C++ compiler know that you are calling C code:
#ifdef __cplusplus
extern "C" {
#endif
void myCFunction();
#ifdef __cplusplus
}
#endif

Should "portable" C compile as C++?

I got a comment to an answer I posted on a C question, where the commenter suggested the code should be written to compile with a C++ compiler, since the original question mentioned the code should be "portable".
Is this a common interpretation of "portable C"? As I said in a further comment to that answer, it's totally surprising to me, I consider portability to mean something completely different, and see very little benefit in writing C code that is also legal C++.
The current C++ (1998) standard incorporates the C (1989) standard. Some fine print regarding type safety put aside, that means "good" C89 should compile fine in a C++ compiler.
The problem is that the current C standard is that of 1999 (C99) - which is not yet officially part of the C++ standard (AFAIK)(*). That means that many of the "nicer" features of C99 (long long int, stdint.h, ...), while supported by many C++ compilers, are not strictly compliant.
"Portable" C means something else entirely, and has little to do with official ISO/ANSI standards. It means that your code does not make assumptions on the host environment. (The size of int, endianess, non-standard functions or errno numbers, stuff like that.)
From a coding style guide I once wrote for a cross-platform project:
Cross-Platform DNA (Do Not Assume)
There are no native datatypes. The only datatypes you might use are those declared in the standard library.
char, short, int and long are of different size each, just like float, double, and long double.
int is not 32 bits.
char is neither signed nor unsigned.
char cannot hold a number, only characters.
Casting a short type into a longer one (int -> long) breaks alignment rules of the CPU.
int and int* are of different size.
int* and long* are of different size (as are pointers to any other datatype).
You do remember the native datatypes do not even exist?
'a' - 'A' does not yield the same result as 'z' - 'Z'.
'Z' - 'A' does not yield the same result as 'z' - 'a', and is not equal to 25.
You cannot do anything with a NULL pointer except test its value; dereferencing it will crash the system.
Arithmetics involving both signed and unsigned types do not work.
Alignment rules for datatypes change randomly.
Internal layout of datatypes changes randomly.
Specific behaviour of over- and underflows changes randomly.
Function-call ABIs change randomly.
Operands are evaluated in random order.
Only the compiler can work around this randomness. The randomness will change with the next release of the CPU / OS / compiler.
For pointers, == and != only work for pointers to the exact same datatype.
<, > work only for pointers into the same array. They work only for char's explicitly declared unsigned.
You still remember the native datatypes do not exist?
size_t (the type of the return value of sizeof) can not be cast into any other datatype.
ptrdiff_t (the type of the return value of substracting one pointer from the other) can not be cast into any other datatype.
wchar_t (the type of a "wide" character, the exact nature of which is implementation-defined) can not be cast into any other datatype.
Any ..._t datatype cannot be cast into any other datatype
(*): This was true at the time of writing. Things have changed a bit with C++11, but the gist of my answer holds true.
No. My response Why artificially limit your code to C? has some examples of standards-compliant C99 not compiling as C++; earlier C had fewer differences, but C++ has stronger typing and different treatment of the (void) function argument list.
As to whether there is benefit to making C 'portable' to C++ - the particular project which was referenced in that answer was a virtual machine for a traits based language, so doesn't fit the C++ object model, and has a lot of cases where you are pulling void* of the interpreter's stack and then converting to structs representing the layout of built-in object types. To make the code 'portable' to C++ it would have add a lot of casts, which do nothing for type safety.
Portability means writing your code so that it compiles and has the same behaviour using different compilers and/or different platforms (i.e. relying on behaviour mandated by the ISO standard(s) wherever possible).
Getting it to compile using a different language's compiler is a nice-to-have (perhaps) but I don't think that's what is meant by portability. Since C++ and C are now diverging more and more, this will be harder to achieve.
On the other hand, when writing C code I would still avoid using "class" as an identifier for example.
No, "portable" doesn't mean "compiles on a C++ compiler", it means "compiles on any Standard comformant C compiler" with consistent, defined behavior.
And don't deprive yourself of, say, C99 improvements just to maintain C++ compatibility.
But as long as maintaining compatibility doesn't tie your hands, if you can avoid using "class" and "virtual" and the the like, all the better. If you're writing open source, someone may want to port your code to C++; if you're wring for hire, you company/client may want to port sometime in the future. hey, maybe you'll even want to port it to C++ in the future
Being a "good steward" not leaving rubbish around the campfire, is just good karma in whatever you do.
And please, do try to keep incompatibilities out of your headers. Even if your code is never ported, people may need to link to it from C++, so having a header that doesn't use any C++ reserved words, is cool.
It depends. If you're doing something that might be useful to a C++ user, then it might be a good idea. If you're doing something that C++ users would never need but that C users might find convenient, don't bother making it C++ compliant.
If you're writing a program that does something a lot of people do, you might consider making it as widely-usable as possible. If you're writing an addition to the Linux kernel, you can throw C++ compatability out the window - it'll never be needed.
Try to guess who might use your code, and if you think a lot of C++ fans might find your code useful, consider making it C++ friendly. However, if you don't think most C++ programmers would need it (i.e. it's a feature that is already fairly standardized in C++), don't bother.
It is definitely common practice to compile C code using a C++ compiler in order to do stricter type checking. Though there are C-specific tools to do that like lint, it is more convenient to use a C++ compiler.
Using a C++ compiler to compile C code means that you commonly have to surround your includes with extern "C" blocks to tell the compiler not to mangle function names. However this is not legal C syntax. Effectively you are using C++ syntax and your code which is supposedly C, is actually C++. Also a tendency to use "C++ convenience" starts to creep in like using unnamed unions.
If you need to keep your code strictly C, you need to be careful.
FWIW, once a project gains a certain size and momentum, it is not unlikely that it may actually benefit from C++ compatibility: even if it not going to be ported to C++ directly, there are really many modern tools related to working/processing C++ source code.
In this sense, a lack of compatibility with C++, may actually mean that you may have to come up with your own tools to do specific things. I fully understand the reasoning behind favoring C over C++ for some platforms, environments and projects, but still C++ compatibility generally simplifies project design in the long run, and most importantly: it provides options.
Besides, there are many C projects that eventually become so large that they may actually benefit from C++'s capabilities like for example improved suport for abstraction and encapsulation using classes with access modifiers.
Look at the linux (kernel) or gcc projects for example, both of which are basically "C only", still there are regularly discussions in both developer communities about the potential gains of switching to C++.
And in fact, there's currently an ongoing gcc effort (in the FSF tree!) to port the gcc sources into valid C++ syntax (see: gcc-in-cxx for details), so that a C++ compiler can be used to compile the source code.
This was basically initiated by a long term gcc hacker: Ian Lance Taylor.
Initially, this is only meant to provide for better error checking, as well as improved compatibility (i.e. once this step is completed, it means that you don't necessarily have to have a C compiler to to compile gcc, you could also just use a C++ compiler, if you happen to be 'just' a C++ developer, and that's what you got anyway).
But eventually, this branch is meant to encourage migration towards C++ as the implementation language of gcc, which is a really revolutionary step - a paradigm shift which is being critically perceived by those FSF folks.
On the other hand, it's obvious how severely gcc is already limited by its internal structure, and that anything that at least helps improve this situation, should be applauded: getting started contributing to the gcc project is unnecessarily complicated and tedious, mostly due to the complex internal structure, that's already to started to emulate many of the more high level features in C++ using macros and gcc specific extensions.
Preparing the gcc code base for an eventual switch to C++ is the most logical thing to do (no matter when it's actually done, though!), and it is actually required in order to remain competitive, interesting and plain simply relevant, this applies in particular due to very promising efforts such as llvm, which do not bring all this cruft, complexity with them.
While writing very complex software in C is often course possible, it is made unnecessarily complicated to do so, many projects have plain simply outgrown C a long time ago. This doesn't mean that C isn't relevant anymore, quite the opposite. But given a certain code base and complexity, C simply isn't necessarily the ideal tool for the job.
In fact, you could even argue that C++ isn't necessarily the ideal language for certain projects, but as long as a language natively supports encapsulation and provides means to enforce these abstractions, people can work around these limitations.
Only because it is obviously possible to write very complex software in very low level languages, doesn't mean that we should necessarily do so, or that it really is effective in the first place.
I am talking here about complex software with hundreds of thousands lines of code, with a lifespan of several decades. In such a scenario, options are increasingly important.
No, matter of taste.
I hate to cast void pointers, clutters the code for not much benefit.
char * p = (char *)malloc(100);
vs
char * p = malloc(100);
and when I write an "object oriented" C library module, I really like using the 'this' as my object pointer and as it is a C++ keyword it would not compile in C++ (it's intentional as these kind of modules are pointless in C++ given that they do exist as such in stl and libraries).
Why do you see little benefit? It's pretty easy to do and who knows how you will want to use the code in future.
No, being compilable by C++ is not a common interpretation of portable. Dealing with really old code, K&R style declarations are highly portable but can't be compiled under C++.
As already pointed out, you may wish to use C99 enhancements. However, I'd suggest you consider all your target users and ensure they can make use of the enhancements. Don't just use variable length arrays etc. because you have the freedom to but only if really justified.
Yes it is a good thing to maintain C++ compatibility as much as possible - other people may have a good reason for needing to compile C code as C++. For instance, if they want to include it in an MFC application they would have to build plain C in a separate DLL or library rather than just being able to include your code in a single project.
There's also the argument that running a compiler in C++ mode may pick up subtle bugs, depending on the compiler, if it applies different optimisations.
AFAIK all of the code in classic text The C programming language, Second edition can be compiled using a standard C++ compilers like GCC (g++). If your C code is upto the standards followed in that classic text, then good enough & you're ready to compile your C code using a C++ compiler.
Take the instance of linux kernel source code which is mostly written in C with some inline assembler code, it's a nightmare compiling the linux kernel code with a C++ compiler, because of least possible reason that 'new' is being used as an variable name in linux kernel code, where as C++ doesn't allow the usage of 'new' as a variable name. I am just giving one example here. Remember that linux kernel is portable & compiles & runs very well in intel, ppc, sparc etc architectures. This is just to illustrate that portability does have different meanings in software world. If you want to compile C code using a C++ compiler, you are migrating your code base from C to C++. I see it as two different programming languages for most obvious reason that C programmers doesn't like C++ much. But I like both of them & I use both of them a lot. Your C code is portable, but you should make sure you follow standard techniques to have your C++ code portable while you migrate your C code to C++ code. Read on to see from where you'd get the standard techniques.
You have to be very careful porting the C code to C++ code & the next question that I'd ask is, why would you bother to do that if some piece of C code is portable & running well without any issues? I can't accept managebility, again linux kernel a big code source in C is being managed very well.
Always see the two programming languages C & C++ as different programming languages, though C++ does support C & its basic notion is to always support for that wonderful language for backward compatibility. If you're not looking at these two languages as different tools, then you fall under the land of popular, ugly C/C++ programming language wars & make yourself dirty.
Use the following rules when choosing portability:
a) Does your code (C or C++) need to be compiled on different architectures possibly using native C/C++ compilers?
b) Do a study of C/C++ compilers on the different architectures that you wish to run your program & plan for code porting. Invest good time on this.
c) As far as possible try to provide a clean layer of separation between C code & C++ code. If your C code is portable, you just need to write C++ wrappers around that portable C code again using portable C++ coding techniques.
Turn to some good C++ books on how to write portable C++ code. I personally recommend The C++ programming language by Bjarne Stroustrup himself, Effective C++ series from Scott meyers & popular DDJ articles out there in www.ddj.com.
PS: Linux kernel example in my post is just to illustrate that portability does mean different meanings in software programming & doesn't criticize that linux kernel is written in C & not in C++.

Isn't saying "C/C++" wrong? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I've seen a lot of questions around that use improperly the expression "C/C++".
The reasons in my opinion are:
Newbie C and C++ programmers probably don't understand the difference between the two languages.
People don't really care about it since they want a generic, quick and "dirty" answer
While C/C++ could sometimes be interpreted as "either C or C++", I think it's a big error. C and C++ offer different approaches to programming, and even if C code can be easily implemented into C++ programs I think that referring to two separate languages with that single expression ( C/C++ ) is wrong.
It's true that some questions can be considered either as C or C++ ones, anyway.
What do you think about it?
C/C++ is a holdout from the early days of C++, where they were much more similar than they were today. It's something that wasn't really wrong at first, but is getting more-so all the time.
The basic structure is similar enough that most simple questions do still work between the two, though. There is an entire Wikipedia article on this topic: http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
The biggest fallacy that comes from this is that because someone is well-versed in C, they will be equally good at C++.
Please remember that the original implementations of C++ were simply as a pre-compiler that output C code for the 'real' compiler. All C++ concepts can be manually coded (but not compiler-enforced) in plain C.
"C/C++" is also valid when referring to compilers and other language/programming tools. Virtually every C++ compiler available will compile either - and are thus referred to as "C/C++" compilers. Most have options on whether to treat .C and .CPP files based on the extension, or compile all of them as C or all of them as C++.
Also note that mixing C and C++ source in a single compiler project was possible from the very first C/C++ compiler. This is probably the key factor in blurring the line between the languages.
Many language/programming tools that are created for C++ also work on C because the language syntax is virtually identical. Many language tools have separate Java, C#, Python versions - but they have a single "C/C++" version that works for C and C++ due to the strong similarities.
We in our company have noticed the following curious fact: if a job applicant writes in his CV about "advanced C/C++ knowledge", there is usually a good chance that he really knows neither ;)
The two languages are distinct, but they have a lot in common. A lot of C code would compile just fine on a C++ compiler. At the early-student level, a lot of C++ code would still work on a C compiler.
Note that in some circumstances the meaning of the code may differ in very subtle ways between the two compilers, but I suppose that's true in some circumstances even between different brands of C++ compiler if you're foolish enough to rely on undefined or contested/non-conformant behavior.
Yes and no.
C and C++ share a lot in common (in fact, the majority of C is a subset of C++).
But C is more oriented "imperating programming", whereas C++, in addition to C paradigm, has more paradigms easily accessible, like functional programing, generic programing, object oriented programing, metaprograming.
So I see the "C/C++" item saying either as "the intersection of C and C++" or "familiarity with C programing as well as C++ programing", depending on the context.
Now, the two languages are really different, and have different solutions to similar problems. A C developer would find it difficult to "parse/understand" a C++ source, whereas a C++ developer would not easily recognize the patterns used in a C source.
Thus, if you want to see how far the C is from the C++ in the "C/C++" expression, a good comparison would be the GTK+ C tutorials, and the same in C++ (GTKmm):
C : GTK+ Hello World: http://library.gnome.org/devel/gtk-tutorial/stable/c39.html#SEC-HELLOWORLD
C++ : GTKmm Hello World: http://www.gtkmm.org/docs/gtkmm-2.4/docs/tutorial/html/sec-helloworld.html
Reading those sources is quite enlightening, as they are, as far as I parsed them, producing exactly the same thing, the "same" way (as far as the languages are concerned).
Thus, I guess the C/C++ "expression" can quite be expressed by the comparison of those sources.
:-)
The conclusion of all this is that it is Ok if used on the following contexts:
describing the intersection of C and C++
describing familiarity with C programing as well as C++ programing
describing compatible code
But it would not be for:
justifying keeping to code in a subset of C++ (or C) for candy compatibility with C (or C++) when compatibility is not desired (and in most C++ project, it is not desired because quite limitating).
asserting that C and C++ can/should be coded the same way (as NOT shown by the GTK+/GTKmm example above)
I think it's more of the second answer - they want something that's easily integrated into their project.
While a C answer may not be idiomatic C++ (and vice versa), I think that's one of C++'s big selling points - you can basically embed C into it. If an idiomatic answer is important, they can always specify C/C++/C++ with STL/C++ with boost/etc.
An answer in lisp is going to be pretty unusable. But an answer in either C or C++ will be directly usable.
Yeah, C/C++ is pretty useless. It seems to be a term mostly used by C++ newbies. We C-only curmudgeons just say "C" and the experienced C++ folks know how much it has diverged from C and so they properly say "C++".
Even if C is (nearly) a subset of C++, this doesn't really have any bearing on their actual usage. Practically every interesting C feature is frowned upon in modern C++ code:
C pointers (use iterators/smart pointers/references instead), macros (use templates and inline functions instead), stdio (use iostreams instead), etc. etc.
So, as Alex Jenter put it, it's unlikely that anyone who knows either language well would say C/C++. Saying that you know how to program in "C/C++" is like saying you know how to program in "Perl/PHP"... sure they've got some significant similarities, but the differences in how they are actually used are vast.
C/C++ often means a programiing style, which is like C and classes, or C and STL :-) Technicaly it is C++, but minimum of its advantages are used.
I agree. I read the C tag RSS feed, and I see tons of C++ questions come through that really don't have anything to do with C.
I also see this exchange a lot:
Asker: How do you do this in C?
Answer: Use the X library for C++.
Asker: OK, how about someone actually answer my question in C?
I use that term myself, and it is because it is my style, I don't use boost, stl or some other things, not even standard C++ libs, like "cout" and "cin", I program C but using classes, templates and other (non-library) features to my advantage.
I can say that I am not a master of C, neither a master of C++, but I am really good at that particular style that I use since 10 years ago. (and I am still improving!)
I was under the impression that all c code is valid c++ code.
Isn’t saying “C/C++” wrong?
No, it isn't. Watcom International Corporation for example, founded more than 25 years ago, called their set of C and C++ compilers and tools "Watcom C/C++", and this product is still developed and available in the open-source form as OpenWatcom C/C++
If it is a complex question needing to write more than one function, yes, it can be wrong.
If it is just to ask a detail about sprintf or bit manipulation, I think it can be legitimate (the latter can even be tagged C/C++/Java/C#, I suppose...).
Whoever is asking the question should write C, C++ or C/C++ depending on the question.
From what I've seen, you can write C++ code the C way or the C++ way. Both work, but C++ code that is not written C style is usually easier to maintain in the long run.
In the end, it all depends on the particular question. If someone is asking how to concatenate strings, than it is very important whether he wants C or C++ solution. Or, another example, if someone is asking for a qsort algorithm. To support different types, you might want to use macros with C and templates with C++, etc.
This was too long for a comment, so I had to make it an answer, but it's in response to Jeff B's answer.
Please remember that the original
implementations of C++ were simply as
a pre-compiler that output C code for
the 'real' compiler.
I have a friend (who writes C++ compilers -- yes, plural), who would take offense to your first sentence. A compiler whose object code is C source code is every bit as much a compiler as any other. The essence of a compiler is that it understands that syntax of the language, and generates new code based on that. A pre-processor has no knowledge of the language and merely reformats its input.
Remember that the C Compilers which would compile the output of those C++ compilers, would themselves output ASM code would would then be run through an assembler.
I tend to put C / C++ in my questions.
Typically I am looking for something that I can use in my c++ application.
If the code is in C or in C++ then I can use it, so I would rather not just limit the possible answers to one or the other.
Not only these two languages are different, but also the approaches are different. C++ is an OO language, while C is procedural language.
Do I have to mention templates?
Also, there are differences in C and C++ standards. If something is good in C, doesn't have to compile in C++

Is it true that there is no need to learn C because C++ contains everything? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this?
Overview:
It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately.
C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function). C++ does change the definition of some terms in C such as structs, although still in a superset way.
Examples of why it is not a strict superset:
This Wikipedia article has a couple good examples of such a differences:
One commonly encountered difference is
that C allows implicit conversion from
void* to other pointer types, but C++
does not. So, the following is valid C
code:
int *i = malloc(sizeof(int) * 5);
... but to make it work in both C and
C++ one would need to use an explicit
cast:
int *i = (int *) malloc(sizeof(int) * 5)
Another common portability issue is
that C++ defines many new keywords,
such as new and class, that may be
used as identifiers (e.g. variable
names) in a C program.
This wikipedia article has further differences as well:
C++ compilers prohibit goto from crossing an initialization, as in the following C99 code:
void fn(void)
{
goto flack;
int i = 1;
flack:
;
}
What should you learn first?
You should learn C++ first, not because learning C first will hurt you, not because you will have to unlearn anything (you won't), but because there is no benefit in learning C first. You will eventually learn just about everything about C anyway because it is more or less contained in C++.
While it's true that C++ was designed to maintain a large degree of compatibility with C and a subset of what you learn in C++ will apply to C the mindset is completely different. Programming C++ with Boost or STL is a very different experience than programming in C.
There was a term of art called using C++ as a better C. This meant using some C++ language features and tools to make C programming easier (e.g., declaring the index variable of a for loop within the for statement). But now, modern C++ development seems very different from C other than a great deal of the syntax and in those cases the C legacy often seems to be a burden rather than a benefit.
It might be true that you don't need to learn the syntax of C if you know the syntax of C++ but you cetainly do need to learn of how coding practices are different in C than in C++.
So your professor wasn't 100% right.
In C you don't have the classes to arrange your code into logical modules and you don't have C++ polymorphism. Yet you still need to achieve these goals somehow.
although the syntax of C is to some extent a subset of C++, programming in C is not a subset of programming in C++. it is completely different.
Yes and no.
As others have already answered, the language C++ is a superset of the language C, with some small exceptions, for example that sizeof('x') gives a different value.
But what I don't think has been very clearly stated is that when it comes to the use of these two languages, C++ is not a superset, but rather different. C++ contains new (it can be discussed if they are better) ways of doing the basic things, such as writing to the screen. The old C ways are still there, but you generally use the new ways. This means that a simple "hello world" program looks different in C and in C++. So it is not really true that the simple things are the same in C and C++, and then you just add more advanced stuff, such as support for object-oriented programming, in C++.
So if you have learnt C++, you will need to re-learn quite a lot before you can program in C. (Well, it is possible to teach C++ as an extension to C, still using printf and malloc instead of iostreams and new, and then adding classes and other C++ things, but that way of using C++ is generally frowned upon.)
No C++ isn't really a superset of C. You can check this article for a more extensive list of the differences if you're interested:
http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B
Not entirely true.
The biggest "gotcha" is typing -- C++ is much more strongly typed than C is, and the preferred methods for solving this in C++ are simply not available in C. Namely, you can silently cast between types in C (particularly pointer types), but not in C++. And C++ highly recommends using the static_cast/reinterpret_cast/const_cast methods for resolving these issues.
More importantly, if you learn C++ syntax and mannerisms, you'll probably find it difficult to deal with C (some may say this is good; and I prefer C++ myself, but sometimes it just isn't an option, or you have to deal with legacy code that's in C and not C++). Again, the most likely issues you'll encounter are dealing with pointers (particularly char*'s and general array usage; in C++ using std::string and std::vector or other collections is simply better).
It's certainly possible to learn C++, and then learn the differences between C and C++ and be capable of programming in both. But the differences are far more than just skin deep.
It is true that for most purposes, C++ contains everything that C does. Language lawyers will be quick to point out that there are some very special edge cases that are valid C but not valid C++.
One such example might be the C declaration
int virtual;
which declares an integer named "virtual". Since "virtual" is a keyword in C++, this is not valid C++.
There is a large common core of C (especially C89) and C++, but there are most certainly areas of difference between C and C++. Obviously, C++ has all the object-oriented features, plus the generic programming, plus exceptions, plus namespaces that C does not. However, there are also features of C that are not in C++, such as support for the (close to archaic) non-prototype notation for declaring and defining functions. In particular, the meaning of the following function declaration is different in C and C++:
extern void function();
In C++, that is a function that returns no value and takes no parameters (and, therefore, is called solely for its side-effects, whatever they are). In C, that is a function which returns no value but for which there is no information about the argument list. C still does not require a declaration in scope before a function is called (in general; you must have a declaration in scope if the function takes a variable list of arguments, so it is critical to #include <stdio.h> before using printf(), etc).
There are also differences:
sizeof('c')
In C++, the answer is 1; in C, the answer is normally 4 (32-bit systems with 8-bit characters) or even 8 (64-bit systems with 64-bit int).
In general, you can write code that will compile under both C and C++ compilers without much difficulty - the majority of my code does that all the time. The exceptions are either a result of carelessness on my part, or because I've consciously exploited the good features of C99 that are not in C++ 98, such as designated initializers, or long long.
Stroustrup himself advices against learning C first. But then again, he (and many others of his generation) managed to become a C++ guru starting from C.
I personally would disagree with your professor.
Generally speaking, C++ is based on C and in that "sense" contains it and extends it.
However, since traditionally people learned C and only then the extensions of C++, your professor's statement is incorrect since to use C++ correctly you would need to master the C origins. It is possible that when teaching you something, your professor or textbook will not specifically mention what came from which language.
In addition, it is important to understand that despite the similarities, not every C program runs in the same way under C++. For example, C structs are interpreted differently (as classes with everything public) by the C++ compiler.
When I teach, I teach the C core first, and then go to C++.
If any of the students in the class intend to become embedded software engineers, then they may have no choice but to program in C (see this question, and this one, among others).
Of course, having learnt C++, it may be less of a transition for them than starting from scratch - but it still makes your professor's statement untrue!