5

I just saw the following code among the successful submissions at codechef.

http://www.codechef.com/viewplaintext/1595846

I used to think that

float max(int n,int arr[n][n])
{....}

is not allowed in C++ (as 'n' is a variable). My CodeBlocks (on windows) with MinGW [gcc 4.4] gives compile time error. that "error: array bound is not an integer constant.

Then how can be such a solution be accepted by CodeChef's judge. Is there any special flag that allows us to do that in C++???

EDIT: A link showing status as AC (accepted) : http://www.codechef.com/viewsolution/1595846

2
  • Seems like illegal c++ to me. Commented Dec 11, 2012 at 10:30
  • 1
    See Abhishek Thakur answer below. This submission is marked as C, not C++, and this happens to be legal in C (though not in standard C++). Commented Dec 11, 2012 at 11:24

2 Answers 2

5

Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression.

Ref: http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html

Sign up to request clarification or add additional context in comments.

4 Comments

Indeed, the submission says it is implemented in C, not C++. So the code is correct according to the C standard.
Thanks. I tried the same code in C, that worked. But what about C++ ? It is giving errors.
@TheCrazyProgrammer You have errors because this is legal C, but not legal C++. C++98 was almost a strict superset of C90, but C99 came later and introduced some additional features such as this. Later versions of the C++ standard have not made a priority of keeping compatibility with C.
Note that, with the C2011 standard, variable-length arrays are now optional; it's up to the implementation do decide whether to support them or not. GCC will probably continue to do so, but compilers that currently don't may choose not to going forward. And yes, C and C++ are different languages, with different semantics, and will probably diverge even further over time. Do not assume any arbitrary C code will compile as C++.
4

I stand corrected: C99 does allow this for C, although many compilers do not implement it yet and some probably never will (microsoft).

Previous answer

Either pass arr as int** or use something like

template< int N >
float max(const int (&arr)[N][N])
{ ... }

which off course requires N to be a compile time constant. The safest solution would be to use a std::vector or some other container that has knowledge about its size.

Overall the code seems pretty fragile to me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.