views:

414

answers:

4

For example result of this code snippet depends on which machine: the compiler machine or the machine executable file works?

sizeof(short int)
+9  A: 

sizeof is a compile time operator.

Billy ONeal
@Billy ONeal: Any thoughts on why it needs to be compile time? [Runtime would have been better, no?](http://codepad.org/aBVjROoU)
Lazer
+7  A: 

It depends on the machine executing your program. But the value evaluates at compile time. Thus the compiler (of course) has to know for which machine it's compiling.

Johannes Schaub - litb
If compiled on 32-bit, and run binary on 64-bit. Is it 2 byte or 4 byte?
ogzylz
@ogzylz, for example `sizeof (void*)` will be 8 if you compile for a 64 bit platform (assuming 8bit chars), regardless of the machine you build the program on. The sizeof of `short int` is unlikely to change.
Johannes Schaub - litb
@Johannes If the 32-bit exe is run on an 64-bit OS the size of objects doesn't change as far as I know. I was under the impression that 32-bit code was run in a subsystem.
anon
@Neil i interpreted him that he has a cross compiler that runs on a 32 bit system and compiles to a 64bit executable. The target definitions for GCC are done by defining suitable macros, for example: http://gcc.gnu.org/onlinedocs/gccint/Type-Layout.html#Type-Layout
Johannes Schaub - litb
ogzylz
+2  A: 

sizeof is evaluated at compile time, but if the executable is moved to a machine where the compile time and runtime values would be different, the executable will not be valid.

anon
@Neil Butterworth: a) By "evaluated", do you mean that "the result of `sizeof` would be calculated at compile time and then hard-coded in the executable"? I used to think so, but now I am not able to explain [how this works](http://stackoverflow.com/questions/2615203/is-sizeof-in-c-evaluated-at-compilation-time-or-run-time/2709634#2709634). b) Also, by "not valid" so you mean that it will not run at all or only that the executable will report wrong results?
Lazer
+3  A: 
#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???

This is because you're running C, not C++. GCC allows this in C++, but in general C++ compilers do not (http://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html).
Peter K.