Green goblin
Green goblin

Reputation: 9994

Does sizeof evaluate at compile-time or runtime?

I am confused about the evaluation time of sizeof operator.
When does the sizeof operator get evaluated?

Does its evaluation time (compile-time or runtime) depend on the language (C? C++?)?

Can we use sizeof in case of objects created at runtime in C++?

Upvotes: 16

Views: 6859

Answers (4)

abelenky
abelenky

Reputation: 64730

In C it is not always a compile time operation, as shown in this code:

#include <stdio.h>
#include <stdint.h>

int main(void) {
    int x;
    scanf("%d", &x);   // Value X is not known until run-time
    
    uint16_t data[x];  // VLA: has flexible size depending on input
    
    printf("Value x is: %d\nSize is: %zu\n", x, sizeof(data));
    // sizeof produces proper results at runtime
    
    return 0;
}

The size of array data is not known until runtime, and the sizeof operator still works correctly.

This is one of several reasons why C++ chooses not to support VLAs.

Upvotes: 1

Varun Chhangani
Varun Chhangani

Reputation: 1206

Compile time , because it's calculate size at compile time."Compile time" is when you build your code - when the compiler converts your source code into IL.

Upvotes: -3

djechlin
djechlin

Reputation: 60848

Almost always compile time. But the following examples might be of interest to you:

char c[100];
sizeof(c); // 100

char* d = malloc(100);
sizeof(d); //probably 4 or 8.  tells you the size of the pointer!

BaseClass* b = new DerivedClass();
sizeof(b); //probably 4 or 8 as above.

void foo(char[100] x) {
    sizeof(x); //probably 4 or 8.  I hate this.  Don't use this style for this reason.
}

struct Foo {
    char a[100];
    char b[200];
};

sizeof(struct Foo); //probably 300.  Technically architecture dependent but it will be
//the # of bytes the compiler needs to make a Foo.

struct Foo foo;
sizeof(foo); //same as sizeof(struct Foo)

struct Foo* fooP;
sizeof(fooP); //probably 4 or 8

class ForwardDeclaredClass;

ForwardDeclaredClass* p;
sizeof(p); //4 or 8
ForwardDeclaredClass fdc; //compile time error.  Compiler
//doesn't know how many bytes to allocate

sizeof(ForwardDeclaredClass); //compile time error, same reason

Upvotes: 13

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272792

In almost all cases, sizeof is evaluated based on static type information (at compile-time, basically).

One exception (the only one, I think) is in the case of C99's variable-length arrays (VLAs).

Upvotes: 26

Related Questions