malioboro malioboro - 1 month ago 5
C++ Question

Why I can use array that initiated with 0 size: Char ch[0];

This is my code:

#include<iostream>
using namespace std;
int main(){
char ch[0];
cin >> ch;
cout << ch;
return 0;
}


input1:

abcdefghijklmnopqrstuvwxyza


output1:

abcdefghijklmnopqrstuvwxyza


(working fine, but I don't know why)

input2:

abcdefghijklmnopqrstuvwxyzab


output2:

abcdefghijklmnopqrstuvwxyzab_


(request an input)

input3:

abcdefghijklmnopqrstuvwxyzabc


output3:
(runtime error)

when output2 request an input, and we put input2,
the output is same output2 (with request an input again),
and output1 or output2 will appear too when we put input1 or input2 in there

Can someone explain this phenomenon? Why it happens?

Answer

An array of size 0 is not valid:

If the constant-expression (5.19) is present, it shall be an integral constant expression and its value shall be greater than zero.

If your compiler accepts it, it is merely a non-standard extension. GCC accepts it but will issue a diagnostic if you add the -pedantic option:

warning: ISO C++ forbids zero-size array ‘arr’ [-pedantic]

Nonetheless, reading into an non-standard array of zero size will undoubtedly give you undefined behaviour.

Comments