tm wrote:
) I know that sizeof is special, but it IMHO fits in my concept also.
)
) When a compiler determines that an expression can be evaluated at
) compile time (without disturbing side effects) it is free to do so.
) Afterwards the compiler can use the result of the function instead.
) The sizeof operator can also be viewed in this way.
No.
Consider the fact that sizeof takes a type, not a value.
This goes beyond C, but I can describe such things also. The concept
of an attribute parameter is helpful here. An attribute parameter
allows the attachment of a function or constant to a type. For
sizeof that would mean that sizeof is a constant which is overloaded
for all types (strange, but in my world constants can have
parameters also). Since C does not provide attribut parameters I can
only show this concept in Seed7:
const integer: sizeof (attr char) is 1;
const integer: sizeof (attr short) is 2;
const integer: sizeof (attr int) is 4;
const integer: sizeof (attr long) is 8;
Beyond attribute parameters Seed7 supports also types as parameters.
So sizeof with a type parameter could be seen also as some
built-in function where the header would look like (again in
Seed7 since C does lack type parameters):
const func integer: sizeof (in type: aType) is ...
Also consider that sizeof doesn't actually evaluate its argument.
Not all arguments are automatically evaluated. The right arguments
of the && and || operators are also not automatically evaluated
(the body of a 'while' statement is also such an example).
Technically such non-evaluated parameters are called closures.
The function decides to evaluate such parameters (even multiple
evaluations are possible). This way closure parameters allow
functions which emulate control structures. C does not provide
closure parameters for user defined functions, but other
languages support this concept. As such sizeof could take a
closure parameter which is never evaluated:
const integer: sizeof (in func char) is 1;
const integer: sizeof (in func short) is 2;
const integer: sizeof (in func int) is 4;
const integer: sizeof (in func long) is 8;
A few trick questions:
does 'sizeof(i++)' increment i ?
With the concept of a closure parameter (see above): NO
does 'sizeof(i++ + i++)' invoke UB ?
With closure parameters: NO, because the parameter is not evaluated.
(To be honest, I'm not sure to the answer of either of those.)
For actual C compilers I guess the answer is also NO
(I have not the time to try this out).
Greetings Thomas Mertes
--
Seed7 Homepage:
http://seed7.sourceforge.net
Seed7 - The extensible programming language: User defined statements
and operators, abstract data types, templates without special
syntax, OO with interfaces and multiple dispatch, statically typed,
interpreted or compiled, portable, runs under linux/unix/windows.