What will happen if we declare Array size as a negative value?
Let us first try to declare an array size as negative.
C++
#include <bits/stdc++.h> using namespace std; int main() { // Declare array with negative size int arr[-2]; arr[0] = -1; return 0; } |
Try to run the above code. You will see that this is giving an error that specifies the error is due to the negative size of the array.
Compiler error:
prog.cpp: In function ‘int main()’: prog.cpp:7:15: error: size of array ‘arr’ is negative int arr[-2]; ^
Why cannot we declare an array with a negative size?
We have seen that declaring array size gives an error. But the question is “Why”?
As per the convention of array declaration, it is mandatory that each time an array is evaluated it shall have a size greater than 0. Declaring array size negative breaks this “shall” condition. That’s why this action gives an error.
How different Programming languages handle declaration of Array size with negative value?
Let us look at how negative size array declaration behaves in different programming languages.
In the case of Python:
Python3
from numpy import ndarray b = ndarray(( 5 ,), int ) b = [ 1 , 2 , 3 , 4 , 5 ] print (b) a = ndarray(( - 5 ,), int ) |
Output:
[1, 2, 3, 4, 5] Traceback (most recent call last): File "main.py", line 5, in <module> a = ndarray((-5,),int) ValueError: negative dimensions are not allowed ** Process exited - Return Code: 1 ** Press Enter to exit terminal
In the case of C language
C
#include <stdio.h> int main() { // Declaring array with negative size int b[-5] = { 0 }; printf ( "%d" , b[0]); return 0; } |
Output:
./e384ec66-a75a-4a93-9af5-52e926ec600a.c: In function 'main': ./e384ec66-a75a-4a93-9af5-52e926ec600a.c:4:8: error: size of array 'b' is negative int b[-5]={0}; ^
In case of C++
C++
#include <iostream> using namespace std; int main(){ int arr[-5]={0}; cout<<arr[0]; } |
Output:
./72b436a2-f3be-4cfb-bf0a-b29a62704bb8.cpp: In function 'int main)': ./72b436a2-f3be-4cfb-bf0a-b29a62704bb8.cpp:4:13: error: size of array 'arr' is negative int arr[-5]={0}; ^
In case of Java
Java
public class NegativeArraySizeExceptionExample { public static void main(String[] args) { // Declaring array with negative size int [] array = new int [- 5 ]; System.out.println(array.length); } } |
Output:
Exception in thread "main" java.lang.NegativeArraySizeException: -5 at NegativeArraySizeException.mainNegativeArraySizeException.java:3)
In case of C#
C#
using System; public class NegativeArraySizeExceptionExample{ static public void Main (){ // Declaring array with negative size int [] array = new int [-5]; Console.Write(array.Length); } } |
Output:
prog.cs(7,32): error CS0248: Cannot create an array with a negative size
In the case of Javascript
Javascript
<script> let arr = new Array(-5); document.write(arr); </script> |
Output:
x.js:1 Uncaught RangeError: Invalid array length
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!