Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As Greg Hewgill said, the typedef means you no longer have to write <code>struct</code> all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.</p> <p>Stuff like</p> <pre><code>typedef struct { int x, y; } Point; Point point_new(int x, int y) { Point a; a.x = x; a.y = y; return a; } </code></pre> <p>becomes cleaner when you don't need to see the "struct" keyword all over the place, it looks more as if there really is a type called "Point" in your language. Which, after the <code>typedef</code>, is the case I guess.</p> <p>Also note that while your example (and mine) omitted naming the <code>struct</code> itself, actually naming it is also useful for when you want to provide an opaque type. Then you'd have code like this in the header, for instance:</p> <pre><code>typedef struct Point Point; Point * point_new(int x, int y); </code></pre> <p>and then provide the <code>struct</code> declaration in the implementation file:</p> <pre><code>struct Point { int x, y; }; Point * point_new(int x, int y) { Point *p; if((p = malloc(sizeof *p)) != NULL) { p-&gt;x = x; p-&gt;y = y; } return p; } </code></pre> <p>In this latter case, you cannot return the Point by value, since its declaration is hidden from users of the header file. This is a technique used widely in <a href="http://www.gtk.org/" rel="noreferrer">GTK+</a>, for instance.</p> <p><strong>UPDATE</strong> Note that there are also highly-regarded C projects where this use of <code>typedef</code> to hide <code>struct</code> is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of <a href="https://www.kernel.org/doc/html/latest/process/coding-style.html#typedefs" rel="noreferrer">The Linux Kernel CodingStyle document</a> for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload