-2
#include <stdio.h>
 
void print(int m, int n, int arr[][n])
{
    int i, j;
    for (i = 0; i < m; i++)
      for (j = 0; j < n; j++)
        printf("%d ", arr[i][j]);
}
 
int main()
{
    int arr[][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int m = 3, n = 3;
    print(m, n, arr);
    return 0;
}

why this code is working in c but not in c++. seems like 2d array as a parameter with this does not work in c++.

Evg
  • 25,259
  • 5
  • 41
  • 83
  • 16
    C++ is not a strict superset of C and never has been. Whoever says that is just wrong – UnholySheep Feb 25 '22 at 18:03
  • 5
    Related: [Where is C not a subset of C++?](https://stackoverflow.com/questions/1201593/where-is-c-not-a-subset-of-c) and https://stackoverflow.com/questions/3777031/what-prevents-c-from-being-a-strict-superset-of-c/3777066 – user17732522 Feb 25 '22 at 18:07
  • 3
    _"...often said that c++ is superset of c but below not following that..."_ this might have been true in 1983 using `Cfront` but this has not been the case for over 30 years. – Richard Critten Feb 25 '22 at 18:07
  • 2
    For a question like this you need to list details not "it doesn't work." Compiler error? (List compiler, exact error code). Runtime error or misbehavior? Also list what you've done to debug and correct. – Dave S Feb 25 '22 at 18:07
  • 5
    It is often said, yes... by people who are wrong and have been for a long time. – Etienne de Martel Feb 25 '22 at 18:08
  • Relatively recent example: `auto`. [C++ meaning](https://en.cppreference.com/w/cpp/language/auto), [C meaning](https://en.cppreference.com/w/c/language/storage_duration) – user4581301 Feb 25 '22 at 18:12
  • "often said" is often wrong. – Pete Becker Feb 25 '22 at 19:10
  • Find out who is often saying that to you, and inform them that they are mistaken. – Eljay Feb 25 '22 at 20:50
  • Could it be the `print` statement in `main`? – Thomas Matthews Feb 25 '22 at 21:26

1 Answers1

2

Linked questions explain all the differences, but answering just for the code in the question,

why this code is working in c but not in c++

Code uses variable length array, VLA for short. C++ simply does not have that, so the code is invalid as C++.

Note that some compilers have extensions which may enable some non-standard features, such as VLA support in GNU C++. But it's generally a bad idea to use those, as there are several popular C++ compilers, and using non-standard extensions stops the code from compiling with other C++ compilers which don't have the same extension (or same syntax for the extension).

hyde
  • 60,639
  • 21
  • 115
  • 176