Path: utzoo!utgpu!utstat!jarvis.csri.toronto.edu!mailrus!purdue!bu-cs!buengc!bph From: bph@buengc.BU.EDU (Blair P. Houghton) Newsgroups: comp.lang.c Subject: When is a cast not a cast? Message-ID: <2747@buengc.BU.EDU> Date: 2 May 89 10:50:51 GMT Reply-To: bph@buengc.bu.edu (Blair P. Houghton) Followup-To: comp.lang.c Organization: Boston Univ. Col. of Eng. Lines: 56 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"