Re: C Interpreter and sizeof operator
- From: Skarmander <invalid@xxxxxxxxxxxxxx>
- Date: Wed, 30 Nov 2005 00:51:40 +0100
ozbear wrote:
Yes. (I know this because I looked up the exact same thing lately.) If x and y have the same type, sizeof x = sizeof y must hold without exception.If one were writing a C interpreter, is there anything in the standard standard that requires the sizeof operator to yield the same value for two different variables of the same type?
6.5.3.4: "The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant."
Note that the *value* of the operand is irrelevant. Only its *type* matters. Therefore the size of an object may *not* depend on its value, but only on its type. If x and y are of type 'int', then sizeof x = sizeof(int) and sizeof y = sizeof(int), therefore sizeof x = sizeof y. Bad Things happen if you violate this.
Let's assume that the interpreter does conform to the range values for, say, type int, but allocates storage for the variables based on their value. So, for two variables foo and bar
int foo = 0; /* interpreter allocates two bytes */ int bar = 200000000; /* interpreter allocates four bytes */
Does the standard require that sizeof foo == sizeof bar thereby making this allocation scheme broken, unless hidden in some way?
Yes.
You can try and fudge this in cases where the application cannot possibly trip over the wrong size, but it's tricky to do this without violating the standard, and in an interpreter it's very unlikely to be of any value. Just pick a constant size for integers (4 bytes happens to be a very common one).
Or is it perfectly acceptable for the sizeof operator to different results?
No, it's not.
S. .
- Follow-Ups:
- Re: C Interpreter and sizeof operator
- From: Christian Bau
- Re: C Interpreter and sizeof operator
- References:
- C Interpreter and sizeof operator
- From: ozbear
- C Interpreter and sizeof operator
- Prev by Date: Re: Why different from expectation
- Next by Date: Re: Why different from expectation
- Previous by thread: Re: C Interpreter and sizeof operator
- Next by thread: Re: C Interpreter and sizeof operator
- Index(es):
Relevant Pages
|