Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><code>typedef</code> is a language construct that associates a name to a type.<br/> You use it the same way you would use the original type, for instance</p> <pre><code> typedef int myinteger; typedef char *mystring; typedef void (*myfunc)(); </code></pre> <p>using them like</p> <pre><code> myinteger i; // is equivalent to int i; mystring s; // is the same as char *s; myfunc f; // compile equally as void (*f)(); </code></pre> <p>As you can see, you could just replace the <em>typedefed</em> name with its definition given above.<br/></p> <p>The difficulty lies in the pointer to functions syntax and readability in C and C++, and the <code>typedef</code> can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.</p> <p>The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.</p> <p>To answer your three questions</p> <ul> <li><p><strong>Why is typedef used?</strong> To ease the reading of the code - especially for pointers to functions, or structure names. </p></li> <li><p><strong>The syntax looks odd (in the pointer to function declaration)</strong> That syntax is not obvious to read, at least when beginning. Using a <code>typedef</code> declaration instead eases the reading</p></li> <li><p><strong>Is a function pointer created to store the memory address of a function?</strong> Yes, a function pointer stores the address of a function. This has nothing to do with the <code>typedef</code> construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.</p></li> </ul> <p>Example:</p> <pre><code>typedef int (*t_somefunc)(int,int); int product(int u, int v) { return u*v; } t_somefunc afunc = &amp;product; ... int x2 = (*afunc)(123, 456); // call product() to calculate 123*456 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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