When is a cast not a cast?

Blair P. Houghton bph at buengc.BU.EDU
Tue May 2 20:50:51 AEST 1989


Here's one that popped up last night/this morning (keep that Sanka
away from me! %-S )

I wanted to be a 'good little programmer' and make all the types
match up, so I was using casts wherever a promotion might be
non-obvious.  In particular, I fell for:  (the line numbers are shown
only for reference)

1   main()
2   {
3	char *c;
4	char *p;
5	int i;
6	...
7	c = "somestring";  /* Nothing fancy, null-terminated. */
8	i = 4;  /* For example. */
9	...
10 	p = (c + (char *) i);  /* More trouble than it's worth... */
11	...
12  }

wherupon both the lint(1) and cc(1) in my Ultrix 2.2 piped-up with
warnings that the 'operands of + have incompatible types' on line 10...

Now, who is having the more serious problem with (reduntantly?) casting
i to be a char * before this addition: me, or the programmming tools
under Ultrix version 2.2?

How can two things explicitly identifiable as being the same type
(one by declaration, the other by that all-powerful fiat, the cast)
be suddenly 'incompatible'?

I have an inkling as to what I'm missing, but it makes little sense
regardless:  It involves getting the integer quantity (i * sizeof(char *))
which leaves one right back in the pigpen wondering how to cast this greater
integer as in 

	p = (c + (char *)( i * sizeof(char *) );

I get the feeling that one isn't allowed pointer arithmetic at all.
It only seems to allow such things as " &(foo[bar]) - foo ", where it
is 100% certain that both operands point to the same data segment.

Additional info:
 - lexical order of c and (char *)i on line 10 above is immaterial;
 - the extra parentheses are immaterial;
 - initialization method is immaterial;
 - declaring c as '(3)  char c[];' changes nothing;
 - declaring i as '(5)  char *i;' then setting '(8)  i = (char *) 4;' convinces
     lint to say:
      'foo.c(10): warning: illegal combination of pointer and integer, op ='
     as well as the same-old-same-old about 'incompatible types';
 - I haven't checked it on other compilers.

				--Blair
				  "Goodness!  A conundrum. `,:-q"



More information about the Comp.lang.c mailing list