2

It's what I believe to be a very simple question.


Context: I'm following a tutorial that allows me to run C++ code in Visual Studio Code, but I'm trying to run C code, not C++ code. The program I'm trying to run is a simple Hello World program (shown below), but this question applies to all C code.

#include <stdio.h>

int main() {
    printf("Hello World!")
}
Acorn
  • 24,970
  • 5
  • 40
  • 69
  • 2
    C and C++ are not the same and you should use a C compiler to compile your code instead. – Tony Tannous Sep 23 '20 at 20:36
  • 2
    C has some features (like variable-length arrays) that are not allowed in C++. You can write valid and correct C code that won't be compiled by a C++ compiler. – Thomas Sablik Sep 23 '20 at 20:37
  • C and C++ branched from a common, that was at the time called C, ancestor decades ago. Since then C has evolved into a better C and C++ became a better C++. Neither look exactly like the root from which they branched. – user4581301 Sep 23 '20 at 20:51
  • no https://godbolt.org/z/ETa8o1 – 0___________ Sep 23 '20 at 20:54
  • Also worth noting that Visual Studio's C support is can be surprising. I believe they now support C11 but not C99. – user4581301 Sep 23 '20 at 20:55
  • `sizeof 'A' == sizeof(char) ? puts("C++") : puts("C");` – Eugene Sh. Sep 23 '20 at 21:01
  • The trivial "hello world" sample you have shown gives the same effect in both C and C++. For more complicated programs, there are examples of C programs that will not compile as C++, others which will compile but give observably different behaviours. There are also some C++ compilers that support features of C even though those features are not valid in C++. – Peter Sep 23 '20 at 21:45

2 Answers2

3

C and C++ are different languages. And even though they share a similar syntax, the semantic meaning of certain constructs are different.

C++ incorporates a large part of C, but it also diverges. You cannot just assume that C code compiled as C++ will give the same result.

You can write code that is both valid C and valid C++ yet mean different things in the two languages.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
1

While C++ can be seen for the most part a superset of C, there are some constructions that are invalid C++ and others that have different behavior.

Instead of dealing with that, tell your compiler to target C instead of C++. All the popular C++ compilers also support C (at least one version).

Acorn
  • 24,970
  • 5
  • 40
  • 69