Richard Tobin said:
No, you should have written something like "the value you get, if any,
is not defined by the rules of C - to get a well-defined result, write
a well-defined program".
If the system the OP is using has a flat address space, and uses those
addresses for C pointers, and performs subtraction of pointers to
distinct objects as if they were in the same object, then he will get
sizeof(int).[/QUOTE]
The C Standard doesn't guarantee this, and no implementation is under
any obligation to provide that behaviour (even setting aside the fact
that there's no prototype in scope for printf and thus the behaviour is
undefined for another reason). Nothing in the rules says that x and y
have to be placed adjacently to each other in memory.
And yet I would like to provide a data point, of no relevance to the
guarantees provided by the Standard, and based purely on empirical
observation on one particular platform (a C8S16ILP32 system with a flat
address space), which seems to echo your point in a very strange way
indeed:
$ cat foo.c
#include <stdio.h>
int main(void)
{
int x;
int y = 1;
int z;
char *p = (char *)&x;
char *q = (char *)&z;
printf("%d\n", (int)(p - q) * y);
return 0;
}
$ ./foo
4
The incursion of y between x and z makes no difference, on this system.
And even if I get y's value at runtime, making it impossible to optimise
it away:
#include <stdio.h>
int main(void)
{
int x;
int y;
int z;
char *p = (char *)&x;
char *q = (char *)&z;
if(scanf("%d", &y) == 1)
{
printf("%d\n", (int)(p - q) * y);
}
return 0;
}
and provide 1 as an input, I *still* get an output of 4. Obviously the
program's behaviour is undefined, but common-sense observation suggests
that the compiler is placing x and z contiguously in memory even though
they are not defined adjacently. Incidentally, swapping y and z around
in the declaration order makes no difference. My compiler is determined
to keep x and z together, come what may. They were made for each other.