1

In a recent post I saw:

scanf("%d" , &TASK_NO);
struct task_info tasks[TASK_NO];
printf("total: %d\n", sizeof(tasks)/sizeof(tasks[0]));

with a comment: "sizeof() is evaluated at compile time, not runtime, so will not give the correct number for total."

In all the history of the C language, sizeof is evaluated at compile time and can be given a declared array (a declared array is something like int a[10]; and sizeof(a) gives 10 times the size of an int). With C99 it is possible to provide the size of an array that is an automatic variable in run time. Does this mean that sizeof for the declared automatic array tasks[TASK_NO] must be evaluated at run time? I.e., has sizeof become something that is sometimes evaluated at run time? If not, is it defined as an error to ask sizeof for a VLA (so the compiler would give a warning/error message as what you are asking is known to not be decidable at compile time)?

Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
  • 1
    Partly good reasoning (well, the actual behaviour limits somewhat those possibilities). Now why don't you check a manual? :) http://en.cppreference.com/w/c/language/sizeof – Karoly Horvath Nov 18 '15 at 17:06
  • @Karoly-Horvath, thanks for the pointer. Makes sense now: since C99 there are runtime requirements placed on `sizeof`. – Paul Ogilvie Nov 18 '15 at 17:18

0 Answers0