Richard Tobin wrote, On 21/02/07 14:22:
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.
Quite so, but we know that they are adjacent on the OP's system (given
the assumptions I listed). Of course, it's possible that adding the
casts to char * may change that, but I doubt it.[/QUOTE]
Even given that they are adjacent and the implementation happens to
produce something that looks sensible there is no guarantee that the
answer will be positive. For example:
markg@brenda:~$ cat t.c
#include <stdio.h>
int main(void)
{
int x, y ;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", (int)(p1-p2));
return 0;
}
markg@brenda:~$ gcc -ansi -pedantic -Wall -W -O t.c
markg@brenda:~$ ./a.out
1
markg@brenda:~$ ssh hal02
markg@hal02's password:
Last unsuccessful login: Mon 19 Feb 00:06:42 2007 on ssh from
staff-vpn20.staff-vpn.causeway.com
Last login: Wed 21 Feb 18:23:26 2007 on /dev/pts/4 from
staff-vpn21.staff-vpn.causeway.com
*******************************************************************************
*
*
*
*
* Welcome to AIX Version 5.3!
*
*
*
*
*
* Please see the README file in /usr/lpp/bos for information pertinent
to *
* this release of the AIX Operating System.
*
*
*
*
*
*******************************************************************************
markg@hal02 ~ $ cat t.c
#include <stdio.h>
int main(void)
{
int x, y ;
int *p1 = &x;
int *p2 = &y;
printf("%d\n", (int)(p1-p2));
return 0;
}
markg@hal02 ~ $ gcc -ansi -pedantic -Wall -W -O t.c
markg@hal02 ~ $ ./a.out
-1
markg@hal02 ~ $
So we have the program (with the undefined behaviour fixed) giving 1 on
one system and -1 on another with both using gcc!
For years, the unix crypt program relied on two arrays being contiguous.
A case of unwarranted chumminess with the compiler, which worked until
someone used a different compiler.
That, indeed, is bad. However, you should probably specify which unix,
since not all versions are the same ;-)