This code snippet
char vec[0];
vec[0] = 1;
invokes undefined behavior.
You may not declare an array with zero elements.
From the C Standard (6.7.6.2 Array declarators)
1 In addition to optional type qualifiers and the keyword static, the
[ and ] may delimit an expression or *. If they delimit an expression
(which specifies the size of an array), the expression shall have an
integer type. If the expression is a constant expression, it shall
have a value greater than zero. The element type shall not be an
incomplete or function type. The optional type qualifiers and the
keyword static shall appear only in a declaration of a function
parameter with an array type, and then only in the outermost array
type derivation.
Pay attention to that there are used incorrect conversion specifiers in these calls of printf
printf("\n SIZEOF: %li", sizeof(vec));
printf("\n VEC[0]: %li", vec[0]);
For a value returned by the operator sizeof
that has the type size_t
you should use the conversion specifier %zu
and for an object of the type char
you should use the conversion specifier %c
.
As for your question
Why "vec[0]" has a size of "0 bytes" even I adding value "vec[0] = 1"
? (If I don't add this value, just declare the vector "char vec[0] or
int vec[0]" the output is same).
then the compiler should issue a message relative to the invalid declaration of an array.
As for the output then as the array is not a variable length array then the value of the expression sizeof( vec )
is evaluated at compile time. The compiler sees that the number of elements is equal to 0
and it calculates the expression sizeof( vec )
as 0 * sizeof( char )
. Thus this expression always yields 0
independent on the array element type.