2

In C

void foo(int size ,int a[][size])
{
    printf("%d\n", a[0][0]);
}
int main(int argc, char const *argv[])
{
    int a[5][5] = {0};
    foo(5, a);
    return 0;
}

works fine

But the same in C++

void foo(int size, int a[][size])
{
    cout << a[0][0] << endl;
}
int main(int argc, char const *argv[])
{
    int a[5][5] = {0};
    foo(5, a);
    return 0;
}

doesnt work. It gives two errors:

 error: use of parameter ‘size’ outside function body
 In function ‘void foo(...)’:
 error: ‘a’ was not declared in this scope

Can anyone explain why this happens. Please also explain any compiler dependent issues either in C or C++..

nbbk
  • 1,102
  • 2
  • 14
  • 32
  • 1
    Check out [this](http://stackoverflow.com/questions/17423902/does-c-allow-vlas-as-function-parameter). – haccks Jul 10 '13 at 18:48

1 Answers1

7

C++ is not a superset of C anymore. You are using the C variable-length array functionality, for which C++ has no equivalent. This is illegal C++ and frankly, it's plain really bad practice. Use std::array and a template. That's what they're for. Because C arrays are terrible.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 3
    "C arrays are terrible" - at least in C++ (In C, we would have a hard time writing programs without them). Also, a `const vector &` would do the job pretty well too, and then you don't even have to do template hackage just to get a simple `.size()` out of the container. –  Jul 10 '13 at 18:45
  • How is it called that property in C that is using the first parameter on the second one (size)? – notNullGothik Jul 10 '13 at 18:47
  • Yes, things stop being terrible if you lower your standards. That's how the Universe works. – R. Martinho Fernandes Jul 10 '13 at 19:00
  • 1
    @R.MartinhoFernandes Let's not start this again. C++ is still not superior to C. C++ programmers are not smarter than C programmers. Neither is it true the other way around. No need for that kind of language war. –  Jul 10 '13 at 19:03
  • I didn't try to draw a distinction where there is none. – R. Martinho Fernandes Jul 10 '13 at 19:09
  • "C++ is not a superset of C anymore." was it ever? – newacct Jul 11 '13 at 01:51