tags:

views:

1041

answers:

23

Is there something that I can do in C but I can't do in C++ ? I stumbled upon the question in a sample interview questions site...

+9  A: 
int new = 0;

works in C, but obviously can't work in C++ because 'new' is a reserved word.

There are some other 'tricks' with reserved words, but other than that, you can pretty much do everything in C that you can do in C++.

Stefan
There are many more difference than just reserved words.
Darron
The question was not about the differences but about what C++ can't do what C can. It should be obvious that there are a lot of differences between the two.
Stefan
Well then I'll rephrase on Darron's behalf: there are many more things which can be done in C but not C++, aside from just using C++ reserved symbols as names.
Steve Jessop
I undid my edit, which strengthened the concluding assertion; I did not realize that C99 had diverged C from being a subset of C++.
Software Monkey
+1  A: 

The short answer is...no, not really. See http://www.research.att.com/~bs/bs_faq.html#difference

Andy Mikula
+3  A: 

You can do almost everything in any of the programming languages. Of course the way of expressing it will vary, as well as the amount of code, clarity of code, ease of further maintenance. Some tasks can be coded with few lines in Prolog and few pages of code in C++, and so on.

Some limiting factors are the available libraries, available compilers, and low-level issues. However when you consider C and C++ on a typical PC, then there is no difference in things that can be done in either of them.

Unless of course you were asking for the differences between C and C++ - for these other people have given you the idea.

Anonymous
"You can do almost everything in any of the programming languages." is good point actually.
erdogany
Just look at the nails and pick up the right hammer...
Anonymous
Church-Turing Thesis, and all that.
Steve Jessop
+2  A: 
char *c = malloc(sizeof(char));

is valid in C, not C++ i.e. automatically casting void*. This of course is a syntax issue, not so much as what you can and cannot _do_ (i.e. accomplish).

codelogic
+6  A: 

There are some things you can say in C wihch you can't in C++ (because C++ has stricter syntax-checking, and C has a more extensive 'legacy' syntax).

Also, there may be some run-time environments (O/S+library+compiler) which support C but not C++, so you can do C on those platforms where you can't do C++.

ChrisW
+13  A: 

In C, you can create array literals ("compound literal"), but in C++ you cannot

/* p points to the first element of an array of 4 int */
int *p = (int[]){1, 2, 3, 4};

You can also create an array with size not yet known at compile time, but C++ has no such possibility ("variable length array"):

// create array. size is known at runtime only.
int p[rand() % 5 + 1];
Johannes Schaub - litb
really good examples I think...
erdogany
What C complier lets you declare varaible length arrays? When I try it, I get "error: expected constant expression"
AShelly
At least VLAs are C99 - how well is it supported?
Arkadiy
AShelly your compiler does not seem to support the last C standard (C99) in that regard. The feature was added after C++ has been standardized ('98)
Johannes Schaub - litb
C99 introduced variable sized arrays. gcc/g++ (4.2.3) supports it. In fact, unless g++ is specifically asked to be strict (-pedantic), it will work in C++ as well.
codelogic
anyway, the interview asks about C . this is C , and the most recent version of it. statements such as "anything you can do in C you can do in C++." were never true. But since 1999, even less so, of course.
Johannes Schaub - litb
... and i guess when you come up with differences that include c99, your employer will see you not only know old school, but modern C too. you can still provide it with c89 vs. c++03 difference (no tentative definitions, no default int, no implicit conversion from void* ...)
Johannes Schaub - litb
AShelly
gcc does not support variable length arrays. They might appear to "work", but they are officially broken. See http://gcc.gnu.org/c99status.html
Chris Young
It might be worth just adding a note into your answer that you're explicitly referring to C99 and not C90.
Richard Corden
i purposely don't mention C99 anywhere in my answer. most talk about C99 as a new language compared to C90, when in fact it "cancels and replaces" C90 (quoted from the draft). i will mention it in the answer, if the question is edited to "C90"/"C89" instead of just plain "C" indeed :)
Johannes Schaub - litb
+5  A: 

Syntactically there are a few things you could write in C that wouldn't compile in C++ (See Incompatibilities Between ISO C and ISO C++ for excruciating details.). If you're asking at a higher level, if there is some program that it's possible to write in C, but not possible to write in C++, then the answer is "No."

Bill the Lizard
+1: you beat me to linking this page...
Christoph
Doesn't seem to have affected the voting. :)
Bill the Lizard
+1  A: 

Is this referring to the latest C standard? The original C standard (ANSI 1989 or ISO 1990, with 1995 updates) is fairly close to being a subset of C++. There's differences, but they're mostly contrived (the biggest exception probably being that void * converts freely with any data pointer in C but not in C++).

However, a new C standard came out in 1999, some time after I'd stopped doing anything in the most modern C. It had new features, some of which are going into the C++ standard due this year or next, but not all.

David Thornley
+20  A: 

Here's a detailed list of C features that are incompatible with C++.

Christoph
+3  A: 

In 'C' you don't need forward declarations. This allows you to pass parameters which are interpreted incorrectly. (Not that this is a great feature, but you can't do it in C++)

in file A:

float sum(float a, float b)
{
   return a+b;
}

in file B

main()
{
  printf("%f\n", sum(1,2));
}

with C, this compiles, but prints 0.000

with C++, you need a float sum(float,float); before the printf, and it gives the expected result.

AShelly
+6  A: 

C++ lacks C99's restrict qualifier. Therefore, there is no way to tell the compiler to perform optimizations based around knowing that pointers aren't aliases.

fizzer
+2  A: 

You can sparsely initialize arrays in C. I like to use it for mapping int->sometype for relatively dense static maps where an unmapped value can be interpreted as 0:

int my_array[] = { [1] = 3, [4] = 2 };
printf("%d %d %d\n", sizeof my_array, my_array[0], my_array[1]);
/* prints 20, 0, 3 */
A: 

C++ does not support named struct member initialization, in C you can do:

struct { int x, y; } a = { .x = 3 };

You can also combine this with the feature shown by Matt Havener:

struct { int a[3], b; } w[] = { [0].a = {1}, [1].a[0] = 2 };

Chris Young
+20  A: 

...that is there anything I can do in C but not in C++.

Both languages are Turing complete, so in theory you can code up equally functional applications in both.

OTOH, C++ is not a superset of C. Especially C99 has some features that C++ does not have. E.g. designated initializers, variable length arrays in structs and as automatic variables. Depending on your "anything", this could be something that C++ cannot do but C can.

wilx
If possible could you please give any simple program which do run in C and not C++
i2ijeya
http://david.tribble.com/text/cdiffs.htm shows quite a lot of examples of differences.
wilx
Many C99 features that aren't in C++ (yet) are already supported by many C++ compilers (especially compilers by vendors that have up to date C99 compilers).
nategoose
+2  A: 

If the criteria is to solve a particular programming problem then both will do the job although it may be a bit easier in some cases to do it in C++ due to the higher level of abstraction

Anders K.
"... although it may be a bit easier in some cases to do it in C due to the lower level of complexity". There. Fixed it for ya'. :)
Dan Moulding
Well if you are into print hello programs I agree.
Anders K.
A: 

"If it can't be done in assembly, it's not worth doing!"

ok, humor aside, I THINK the OP is asking syntactically, rather than operationally.

I think that there are a few obscure things that are legal in C (at least C89) that are not legal in C++, or at least deprecated... But (if they exist) they're pretty obscure. C++ is functionally a superset of C.

Brian Postow
Good point. Really the only difference is syntactical. If there were an operational advantage (on top of the existing syntactical advantage) to C over C++ compilers, I'd be extremely interested.
Matt Joiner
Well, C++ compilers' name mangling is not inter-operable in the way that C compilers' is. Linking multiple C libraries built with different compilers is doable. Linking multiple C++ libraries built with different compilers: not so much.
Nathon
@nathon Excellent point.
Brian Postow
I mentioned two operational advantages in my answers - creating portable libraries and writing programs for a platform that only has a C compiler. Though I can't think of a concrete example for the latter.
Rolf Hendriks
+5  A: 

Quite a few things. For example, in C you can write code like this:

void * v = 0;
char * p = v;

and you can create arrays like this:

int main() {
    int n = 42;
    int a[n];
    return 0;
}

neither of which will compile under C++.

anon
In that last example, I think you might need C99 (or gcc).
Emil
C99 is what C is.
anon
@Neil: Well I agree with you, but I can imagine some people wouldn't.
Emil
+3  A: 

Actually, I can think of one example:

When you create a library (.lib file or .dll file) to be shared by other applications, you're better off using C instead of C++ because the results are more portable. You can do this within a C++ compiler by using an 'extern "C"' block though.

Specifically, C++ has a quirk where there is no standard convention for name mangling - for translating your library's function signatures into more low level names used by the compiler. So for example if you have a function like 'int addNumbers (int a, int b)', different C++ compilers may translate this function into different names, which can lead to problems when you want to import the library. If you use a C compiler or surround your library importing and exporting code with a C block though you won't see this problem, since there is only one way to mangle function names in C.

Rolf Hendriks
Actually, C does not specify a standard ABI.
anon
This is why extern "C" exists.
Joel
C does not specify any ABI, but is simple enough that everybody agreed to use the same ABI. Unlike C++.
el.pescado
+33  A: 

Declare a variable named 'class', as in:

int class = 0;
Sjoerd
This one made me smile.
PeterK
One of the best ways to ensure no one ever compiles your code on a `C++` compiler :D
ereOn
Except that you can. The preprocessor is part of the language and there is no clause that you can not redefine a keyword with the pp.
Luther Blissett
@Luther: true the pp is part of the language specification. Nevertheless, if you use something like `#define class blah` and the above declaration, then your variable is *not* named `class`. It's named `blah`, since everything in the standard, including the names of things, is talking about what happens after macro replacement. Try it for something with external linkage...
Steve Jessop
@Luther: Actually, if you include any standard library headers, it is prohibited to define as a macro an identifier that is lexically identical to a keyword. So in any translation unit that includes a standard library header, `#define class blah` is invalid (off the top of my head, I don't know whether it renders the source ill-formed or just results in undefined behavior).
James McNellis
@James: #define class blah #include "that_header.h" #undef class
Sjoerd
@Sjoerd: _A translation unit that includes a header shall not contain any macros that define names declared or defined in that header. Nor shall such a translation unit define macros for names lexically identical to keywords_ (C++03 §17.4.3.1.1). Note that "a header" here specifically means "a standard library header."
James McNellis
@James: Thanks for the quote. It is clearly not allowed to #define class for a small part of our header. My expectation was that it was possible as long as the define would be undone at the point any standard library header was included; I was wrong.
Sjoerd
A: 

C++ is obviously not a superset of C for a very simple reason: New keywords have been added to C++
class, virtual, new, etc and thus can no more be used as identifiers in C++.

Some of the reasons are subtler.
You can find an exhaustive answer to this question on Bjarn Stroustrup's website: The C++ programming language | Appendix B

Ugo
Your comment misses the point but I really liked your link on Bjarn Stroustrup's site, which highlights subtle C/C++ differences in great detail.
Rolf Hendriks
+2  A: 

Write a program for a platform that supports C but not C++.

Does anyone know of any examples?

Rolf Hendriks
What is that supposed to mean?
Nathon
Some platforms may have a C compiler but no C++ compiler. Either because a C++ compiler has not yet been ported or because its cost (money) is higher.
dolmen
There exist C++ -> C compilers, for example Comeau, so "doing it in C++" isn't entirely out of the question. There may still be library issues, I've never used it for anything other than checking standard compliance.
Steve Jessop
Right, I'm looking for an example of a platform for which a C compiler was written but not a C++ compiler - probably for cost or performance reasons. I don't know of one but I would bet such platforms exist.
Rolf Hendriks
So, is this an answer or a question?
Hans Passant
+2  A: 

The 1998 C++ standard has a list of incompatibilities with the 1990 C standard that is 13 pages long (Annex C). Granted, it's not a lot, compared to the amount of pages that describe the languages, but still covers quit a bit of ground.

Quick summary of the kind of differences that it lists:

  • New keywords are added (any C program that uses them as identifiers is not C++)
  • Type of character literal changed from int to char (compare sizeof('a') in C and C++!)
  • String literals made const (can't do char* q = expr ? "abc" : "de";)
  • "Tentative definitions" are removed from the language.
  • "Compatible types" are removed from the language.
  • Converting from void* to any other pointer now requires casting.
  • Converting from any const/volatile pointer to void* now requires casting.
  • "Implicit declarations" are removed from the language.
  • Expressions can no longer create new types (as in p = (void*)(struct x {int i;} *)0; )
  • results of some expressions became lvalues (compare sizeof(0, arr) for char arr[100];)

...that was the first 3 pages of Annex C.

If you go to the 1999 C standard, the differences are going to take forever to describe. Although C++0x did include some of C99 features, many of them are just inherently incompatible, like the complex type.

Cubbi
A: 

in c, variable declared inside function are public whereas in c++ , data members (variable) declared in default as Private..

sankar
I think you need to learn both C and C++ before commenting on either.
Amardeep
i think what he's trying to refer to is that in C++ structs are like classes but with public default scope - so they're quite different from C structs. Either way, it still doesn't address the issue of something you can do in C that you can't do in C++.
Rolf Hendriks