#include<stdio.h>
void f(int n)
{
    char pp[n];
    printf("%d\n",sizeof(pp));
}
int main()
{
    int n;
    scanf("%d",&n);
    f(n);   
}

In this program the size of array is defined at runtime,and sizeof operator is printing correct size after runtime initialisation in gcc 4.4. Can anybody explain? we say that sizeof is compile time operator.then ? and C99 give us to have this type of initaliazation. pp[n], it is dynamic.but it is still working ? (above snippet is working correctly in .cpp and .c both correcttly.) thanks alot.

In C99 sizeof is not a compile-time operator when used on variable-length arrays. It's still a compile-time operator when used on anything else though.

In C++ your code is not legal. If your compiler accepts it, that means it supports variable-length arrays for C++ as a non-standard extension. gcc will accept VLAs in C++ when in GNU mode (-std=gnu++03 or -std=gnu++11), but will reject them when in standard-compliant mode (-std=c++03 or std=c++11). In C++ as it is defined by the standards, sizeof is purely a compile-time operator. In C++ extended with VLAs it is not a compile time operator when used on VLAs - just like in C99.

Comments
Good explanation!

so, in C++ if i have this code and it is not written anything else about compiler extensions, then what would i say about this code in front of me ? it's very very good explaination which you have given, but all these are when i know about extensions and all. it is a question which will be asked to me in a MCQ type problem, so can you please tell me this ? thanks a lot.

If you have that code in C++ and you're not using any extensions, it will simply not compile. So if you were asked in a test about standard C++, what the output of that code is, the answer would be "Nothing - it does not compile". And if that's not one of the options the test is either not about standard C++ or it's simply wrong.

what about in .c file ? you have considered the case when it is cpp , when it is C then ? is it still compile time operator ? or there is any exception with this also ? thanks.

I think I've answered this in my first post in this thread (for C99 at least):

In C99 sizeof is not a compile-time operator when used on variable-length arrays. It's still a compile-time operator when used on anything else though.

If we're talking about C89, the same thing as for C++ applies: Barring compiler-specific extensions that allow non-standard code to compile, sizeof is always a compile-time operator in C89.

If we're talking about C11, it's basically the same as for C99, but with the caveat that variable-length array are an optional feature in C11. So: in C11, if __STDC_NO_VLA__ is set, sizeof is always a compile-time operator - otherwise it is only a compile-time operator when not used with variable-length arrays.

This article has been dead for over six months. Start a new discussion instead.