74

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.

18
  • 14
    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, 2019 at 16:14
  • 28
    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, 2019 at 19:29
  • 41
    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, 2019 at 19:53
  • 5
    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. Apr 24, 2019 at 20:51
  • 4
    I like to think they did this for esthetic reasons -> looks like it's pointing somewhere, so it's appropriate with pointers.
    – Barmar
    Apr 25, 2019 at 16:26

5 Answers 5

71

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.

2
  • 25
    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. Apr 25, 2019 at 12:56
  • 2
    I have a strong suspicion that if one were to define struct { unsigned char BYTES[4];}; int foo;, one could probably do something like foo.BYTES[1] to access the second byte of foo, while foo->BYTES[1] would access the byte whose numerical address is one greater than the value stored in foo. Two different behaviors, both of which could be useful under different circumstances.
    – supercat
    Jul 23, 2021 at 20:11
72

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.

6
  • 16
    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, 2019 at 18:55
  • 8
    @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, 2019 at 1:15
  • 3
    Would this also mean that structure member names had to be globally unique? Apr 25, 2019 at 12:45
  • 5
    @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, 2019 at 14:55
  • 1
    @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, 2019 at 15:10
46

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.

7
  • 27
    I love it. "K&R C had type inference, but it always inferred int". Brilliant. Apr 25, 2019 at 11:56
  • 13
    "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, 2019 at 14:00
  • 3
    "The coder is assumed to know what she's doing" is more a bad, bad, bad excuse than a philosophy. See the continued growth of Undefined Behavior with each standard, and Torvalds' rants.
    – hmijail
    Sep 4, 2020 at 6:11
  • @hmijailmournsresignees: The authors of C89 generally classified actions as Implementation-Defined or Undefined Behavior based upon whether they wanted to require that all implementations specify the behavior. In situations where all implementations for commonplace platforms would process a construct identically, the authors of the Standard didn't think it should matter whether the Standard defined the behavior, or whether implementations for commonplace platforms unanimously extended the semantics of the language by defining the "officially" undefined behavior.
    – supercat
    Dec 14, 2020 at 18:39
  • 3
    @hmijailmournsresignees: The growth of Undefined Behavior and Torvalds' rants are a consequence of the Standards' application of the term "Undefined Behavior" to actions which most implementations should be expected to process meaningfully, but which might behave unpredictably on implementations intended for unusual hardware, or specialized for some particular kinds of tasks. "The coder is assumed to know what she's doing" would be fine, if interpreted as "The coder is assumed to know more about what actions would be meaningful on a particular target than the compiler writer ever could."
    – supercat
    Dec 16, 2020 at 16:00
23

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.

3
  • 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, 2019 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, 2019 at 16:57
  • 2
    I think this is the best answer, C (and thus C++)'s use of -> is a feature not a bug. Apr 25, 2019 at 13:46
19

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.

2
  • 1
    "The critical thing here is that these two operations are not the same." - I think that is indeed the critical point. The syntax is different because they are fundamentally different operators. The dot operator could as easily be used for array access too - as array.0 or array.i instead of array[0] and array[i] - but in the days before IDEs, the distinction in operator syntax indicated the intended operator and argument type explicitly, and overloading operators according to argument type (even if feasible) would have been less clear for human readers and prone to subtle errors.(1/2)
    – Steve
    Jan 30, 2022 at 17:16
  • Note also that access operators are fundamentally concerned with calculating relative memory offsets for sequentially stored fields. Natively there are only memory indexes. Array access allows memory offsets to be calculated by field index. Structures allow memory offsets to be calculated by field name, and with regard to the memory length of anterior fields (of varying type) in the same structure. Dereferencing pointers is a different concept entirely, not at all involving offsets calculable at compile time, but moving to a memory index determined at run time. (2/2)
    – Steve
    Jan 30, 2022 at 17:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .