Why sizeof (array A[n]) without n defined in C++is fixed?

180 Views Asked by At

When I try to find the sizeof(A) where A is of type int with size as 'n', n is an int that is not defined. I get an output of 496 and when I give a value to n and then check it, sizeof(A) gives me the same values of 496. I know Array is a static data type so it will have memory irrespective of 'n' but can anyone explain me where the value 496 came from?

int main()
{
    int n;
    int A[n];
    
    cout<<sizeof(A)<<"\n";
    
    cin>>n;
    
    cout<<sizeof(A);
    return 0;
}
2

There are 2 best solutions below

2
On BEST ANSWER

where A is of type int with size as 'n'

int n;
int A[n];

The type of A is not "int with size as 'n'". The type of A is int[n] which is array of n integers. However, since n is not a compile time constant, the program is ill-formed. If we were to look past the ill-formedness, the value of n is indeterminate. Reading an indeterminate value results in undefined behaviour.

anyone explain me where the value 496 came from?

It came from undefined behaviour. You can find more details by reading the assembly of the compiled program that produced that result.

0
On

The first cout statement cout<<sizeof(A)<<"\n"; in your code is giving 0 as output. Irrespective of what I take n as input, the next cout statement is also giving a 0. There are two declarations here, int n and int A[n]. As a beginner, it is fair to assume that n remains the same in both cases or has the same value, therefore the size shouldn't change. However, one is an integer(n), the other is an array of integer(A[n]). That makes all the difference!

The first time you print the size of A[n], you are getting a 0 because the array is only declared and not initialized so we know it's empty. The next time, you are taking n as an input, so its size should be 4 bytes(try it yourself) because it's an integer.

Having said that, it really depends on the type of compiler or operating system you are using. I got 4 as an output in one of the online compilers and when I tried implementing it on codeblocks and vscode, I got 32 and 80 respectively. Essentially, this is an undefined behaviour even if n had a garbage value!