59

In the C programming language, the syntax to access the member of a structure is

structure.member

However, a member of a structure referenced by a pointer is written as

pointer->member

There's really no need for two different operators. The compiler knows the type of the left-hand value; if it is a structure, the first meaning is evident. If it is a pointer, the second meaning is evident. Furthermore, . is far easier to type than ->. Not only does -> have more characters to type, on many keyboards one character is unshifted and the other character is shifted, requiring some finger acrobatics. Indeed, many languages based on C allow or use . in place of ->.

Why did C use two operators when one would have sufficed?


Update: As this is the Retrocomputing site, it is implied that questions are asked from a historical perspective. To that end, I have added the tag, and accepted the answer that provided the best historical context.

A few answers took a more speculative approach; a few others raised concerns that became valid later. These are fascinating answers, and I appreciate those who wrote them, but they don't address the history of the decision.

I dislike answering my own questions. However, I did find a paper by Dennis Ritchie that helps to answer this question, and has not been addressed in other answers. I therefore wrote an answer, which you are welcome to examine below.

  • 11
    You can still write (*structure).member, if you like that more. (I don't, very probably K&R didn't, either. It is a bit awkward to handle because of C operator precedence, and that might answer your question) – tofro Apr 24 at 16:14
  • 21
    Just out of curiosity: In your hypothetical language where a.b could be interpreted as (*a).b if a is a pointer-to-struct, would it also be automatically be interpreted as (**a).b if a is a pointer-to-pointer-to-struct? Just to point out a possible consequence… – wrtlprnft Apr 24 at 19:29
  • 32
    People complain a lot about pointers being confusing. Imagine adding to that confusion by not knowing if a variable was a pointer or not when reading code. – JPhi1618 Apr 24 at 19:53
  • 3
    Just to note: Wirth's language Oberon does almost exactly this, allowing the Pascal-like ^ to be omitted in the expressions p^.x and p^[i], and using types to disambiguate. – Mike Spivey Apr 24 at 20:51
  • 2
    Basically the same question on SO: stackoverflow.com/questions/13366083/… – DaveInCaz Apr 25 at 18:25
47

Some of the first C code I saw was like this: 0x8040->output = 'A'; — its purpose was accessing memory mapped I/O locations.  Needless to say it took me a while to figure out what this code was supposed to do, and the hex constant there really threw me.

The original K&R C placed all field names (here output) into the same namespace.  It was an error to have two fields of the same name in different structs at different offsets — but ok to have the same name at the same offset, the idea here being that two different structs could share the same initial fields, giving cheap way of doing "subclassing" to put varying data members at the end of the struct.

A struct could also be anonymous, e.g. no tag name for the struct.  None the less, the members could still be used in . or -> expressions.

The C Programming Language (K&R C) Appendix A, p197,209

[8.5] ... Two structures may share a common initial sequence of members; that is, the same member may appear in two different structures if it has the same type in both and if all previous members are the same in both.  (Actually, the compiler checks only that a name in two different structures has the same type and offset in both, but if the preceding members differ the construction is nonportable.)

...

[14.1] ... §7.1 says that in a direct or indirect structure reference (with . or ->) the name on the right must be a member of the structure named or pointed to by the expression on the left.  To allow an escape from the typing rules, this restriction is not firmly enforced by the compiler.  In fact, any lvalue is allowed before ., and the lvalue is then assumed to have the form of the structure of which the name on the right is a member.  Also, the expression before a -> is required only to be a pointer or an integer.  If an integer, it is taken to be the absolute address, in machine storage units, of the appropriate structure.

Since the K&R language and compiler didn't care what the type of the left hand side of . and -> was, the only way it had to tell the difference was by having the two operators.

The ANSI C line of standards simply followed suit in syntax, even as these old rules were abandoned.

  • 10
    Aha, so that’s why POSIX struct member names are all prefixed (e. g. stat::st_uid). I thought it was to enable shenanigans like #define st_atime st_atim.tv_sec. – Roman Odaisky Apr 25 at 12:56
61

In the embryonic form of C described in the 1974 C Reference Manual, there was no requirement that the left operand of . actually be a structure, nor that the left operand of -> actually be a pointer. The -> operator meant "interpret the value of the left operand as a pointer, add the offset associated with the indicated structure member name, and dereference the resulting pointer as an object of the appropriate type. The . operator effectively took the address of the left operand and then applied ->.

Thus, given:

struct q { int x, y; };
int a[2];

the expressions a[0].y and a[0]->y would be interpreted in a fashion equivalent to ((struct q*)&a[0])->y and ((struct q*)a[0])->y, respectively.

If the compiler had examined the type of the left operand to the . operator, it could have used that to select between the two behaviors for it. It was probably easier, however, to have two operators whose behaviors didn't depend upon the left operand's type.

  • 11
    To the point. As well as the last part about being 'easier'. C wasn'T designed to be a language as comfortable as possible, but to be translated as linear as possible. Resolving contextual information adds complexity and ambiguity. Nothing one wants t have when the task is to write an OS as close to the machine as possible while having the luxury of structured programming support. – Raffzahn Apr 24 at 18:55
  • 4
    @Raffzahn: Even in 1974 C, the contextual information had be kept to process the + operator, so the cost of using the already existing information to disambiguate . and -> would have been minimal if there was no need to use them with other types as well. – supercat Apr 25 at 1:15
  • 1
    Would this also mean that structure member names had to be globally unique? – IllusiveBrian Apr 25 at 12:45
  • 3
    @IllusiveBrian exactly. See e.g. the names of fields in struct tm (described e.g. in ctime(3)): they are like tm_sec, tm_min, tm_hour etc.. Similarly struct stat (see stat(2)), which has st_dev, st_ino etc.. These are redundant in modern C, but have to be preserved for backwards compatibility – Ruslan Apr 25 at 14:55
  • @Raffzahn: In simple compilers, the primary cost of having a compiler use various information to select what kind of operation an operator will perform is generally making sure the compiler will have the information in the context where it is needed. A compiler that has scanned an expression as far as p=thing will need to know whether type of thing is a pointer or array, and the target/element type, if the next token is a +. Consequently, no special effort should be required to ensure that it has that information if the next token happens to be a . or -> instead. – supercat Apr 25 at 15:10
37

Despite your assertion, there would in fact be situations where it would be ambigious.

First off, early C compilers were very simple. This was in fact the main appeal of the language, as compilers for it were very easy to create and could run on very small systems, like early 16/32 microprocessors.

Adding a bunch of code for hitting all the niche cases of type inference would have drastically added to the amount of code required to make a C compiler. In fact, I've argued as a (half) joke that K&R C had type inference, but it always inferred int. If you didn't tell C what type an object was, it assumed int (which could cause some really gnarly bugs, let me tell you...)

Secondly, since K&R C was weakly (barely) typed, the information in many cases flat out wasn't available. The destination type of a pointer assignment can be an int, or vice versa, and K&R C has no problem with that. The compiler simply cannot infer a dereference. The coder is assumed to know what she's doing.

Also realize that in C pointers and arrays are essentially syntactic sugar for each other. This means now your . operator would have to automagically work on arrays too. For instance, if member happened to be a char array, now structure.member would return with the first character. And again, both chars and pointer are assignable into ints, so context doesn't help you.

This being said, you aren't the first to notice this issue. In fact, Ada was designed that dereferencing a pointer object is always assumed when a dot is used. In those cases where you want the actual pointer, you have to use .all. The ambiguity (pointer vs. pointed to object) is still there, but resolved by moving the extra syntax to the weirder case.

  • 12
    I love it. "K&R C had type inference, but it always inferred int". Brilliant. – Peter A. Schneider Apr 25 at 11:56
  • 8
    "The coder is assumed to know what she's doing" is the C philosophy in a nutshell. That's simultaneously C's greatest strength and greatest weakness. – John Bode Apr 25 at 14:00
19

I think there are two factors that led to standardization of the distinct operator "->" for accessing data members using a pointer.

  1. You assume that the C compiler would recognize the type of the LHS as being a pointer. But programmers could, and often did, override the initial typing (variable declaration) by using a typecast.
  2. In order to make the code more readable and less prone to unintended side-effects, it is useful to distinguish operations using pointers.

A very common feature of idiomatic C code is that a structure passed to a function as a pointer is modified within the function. Thus, the result is returned implicitly, by the side-effect of the structure variable in the calling function having been modified by the callee. This sort of approach violates modern sensibilities about loosely coupled code, but it was a simple and efficient means of dealing with complexity in C code. I would say the programmer was greatly assisted in maintaining the readability of such code by having distinct operations that made it clear whether some (possibly shared) memory pointer was the thing whose target was being modified.

  • Could you give an example of your point #1? The type of the result of a typecast is well-defined... it's the type you are typecasting to. Should that be a pointer to a structure, the compiler has enough information to access its members. Whatever the type was prior to the typecast is irrelevant. – DrSheldon Apr 24 at 16:27
  • 1
    @DrSheldon Yes, you are correct. The compiler can check operators used against the type of a typecast too, and interpret a single operator appropriately. But then you are removing one of the compiler checks against programming errors. I think #1 and #2 actually work in concert to push the programmer toward care with pointer references. If the compiler tries to be "too smart" it ends up misinterpreting what the error-prone programmer intended, and (perhaps more important) makes the code harder to read. – Brian H Apr 24 at 16:57
  • I think this is the best answer, C (and thus C++)'s use of -> is a feature not a bug. – Jack Aidley Apr 25 at 13:46
6

I dislike answering my own questions. To that end, I have accepted the answer that is supported by the most historical sources. (Retrocomputing is about actual history, after all.) However, I'm not yet satisfied that the other answers completely answer the question.


Dennis Ritchie, the creator of the C language and co-creator of Unix, presented a history of C at an ACM conference in April 1993. The conference proceeding is available online as The Development of the C Language, and is quoted below.

C evolved from the short-lived B language, which in turn derived from BCPL. These two prior languages were typeless. All variables were word-sized values, which could represent signed integers, unsigned integers, characters, or pointers. Pointers could be used to reference the elements of arrays, strings, or data structures. The type that a word represented depended on the operators being used on it. As Ritchie noted,

Both languages are typeless, or rather have a single data type, the 'word,' or 'cell,' a fixed-length bit pattern. Memory in these languages consists of a linear array of such cells, and the meaning of the contents of a cell depends on the operation applied. The + operator, for example, simply adds its operands using the machine's integer add instruction, and the other arithmetic operations are equally unconscious of the actual meaning of their operands.

Ritchie's paper goes in depth about how the syntax for arrays developed. In BCPL, memory was accessed with the syntax pointer!offset. B changed memory access to a unary prefix operator *. Arrays could then be accessed with the expression *(array+offset). To "sweeten such array accesses", Ritchie added the now-familiar syntax array[offset] to B.

Structures didn't exist in BCPL or B; they were introduced in C. Ritchie doesn't discuss the history of structures as much as he does arrays. However, it does seem that early versions of C continued the practice that the meaning of a value was determined by the operators that used it. Ritchie notes:

Beguiled by the example of PL/I, early C did not tie structure pointers firmly to the structures they pointed to, and permitted programmers to write pointer->member almost without regard to the type of pointer; such an expression was taken uncritically as a reference to a region of memory designated by the pointer, while the member name specified only an offset and a type.

and

Compilers in 1977, and even well after, did not complain about usages such as assigning between integers and pointers or using objects of the wrong type to refer to structure members.

He doesn't explicitly explain the origins of . and ->, but it is reasonable to conclude that their purpose was to simplify expressions (much like [] did for arrays). As many have noted, pointer->member is a shorter way to write *(pointer+member). Similarly, variable.member is a shorter way to write *(&variable + member).

The critical thing here is that these two operations are not the same. Considering that embryonic C continued the tradition of leaving the determination of type to operators, two different operators were therefore needed. Embryonic C was not sophisticated enough to "know" the type of operands.

As C matured, later compilers would have enough information to make the distinction. However, Ritchie notes the importance of backward-compatibility for existing code, even as the language was evolving:

As should be clear from the history above, C evolved from typeless languages. It did not suddenly appear to its earliest users and developers as an entirely new language with its own rules; instead we continually had to adapt existing programs as the language developed, and make allowance for an existing body of code.

0

Just an aside: If the operator '*' were suffix not prefix, it would be neater; it would be yet neater if the suffixed reference-following operator were actually '.', as, I believe, it was in a language whereon C was based. In C p->f is sugar for (*p).f, but with suffix operator the sugar would be useless: p*.f or p..f . Years ago this was noticed, by whom I know not. I feel that one would be less tempted to wish '->' away.

  • 2
    This doesn't answer the question. Please read the tour. – wizzwizz4 Apr 26 at 6:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.