D
D
Dmitry Threy2016-05-09 00:54:40
C++ / C#
Dmitry Threy, 2016-05-09 00:54:40

C code that won't work in C++?

Extract from Wikipedia :

The C++ syntax is inherited from the C language. One of the design principles was to maintain compatibility with C. However, C++ is not strictly a superset of C; The set of programs that can be translated equally well by both C and C++ compilers is quite large, but does not include all possible C programs .

And at Laforet I met such a statement that not every C code will be compiled by the C ++ compiler . There is nothing to argue about, but as far as I remember, all C language functions are supported in C ++. Backwards compatible!
But is it possible to find out exactly which code will not compile?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Maxim Moseychuk, 2016-05-09
@more_cry

Variable Length Arrays (VLA).

#include "stdio.h"

int main() {
 size_t n;
 scanf("%Iu", n);
 int array[n];
 return 0;
}

But it all depends on the compiler and the strictness of following the standard. The GNU compiler, for example, introduces such arrays for C++ in extensions.
There are also variables in C restrict, register variables, which are not present in C++.

R
Rou1997, 2016-05-09
@Rou1997

Anyone will work. I will rename the file from .cpp to .c and whatever will work.

J
jcmvbkbc, 2016-05-09
@jcmvbkbc

Here is an example with two files that compiles as both C and C++, but only links as C. The difference between languages ​​is in the C tentative definition:
File ac:

int i;

int main()
{
    i = 1;
    return 0;
}

bc file:
int i;

int f(void)
{
    i = 1;
    return 0;
}

$ gcc -std=c89 a.c b.c -o a
$ gcc -std=c99 a.c b.c -o a
$ gcc -std=c11 a.c b.c -o a
$ g++ a.c b.c -o a
/tmp/cc8AfU2T.o:(.bss+0x0): multiple definition of `i'
/tmp/ccBOJ29v.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

R
rhaport, 2016-05-24
@rhaport

typdef enum
{
  zero,
  one,
  two
} t_numbers;

int main()
{
   t_numbers x;
   x = 2;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question