Rectangle 27 738

The common idiom is using both:

typedef struct X { 
    int x; 
} X;

They are different definitions. To make the discussion clearer I will split the sentence:

struct S { 
    int x; 
};

typedef struct S S;

In the first line you are defining the identifier S within the struct name space (not in the C++ sense). You can use it and define variables or function arguments of the newly defined type by defining the type of the argument as struct S:

void f( struct S argument ); // struct is required here

The second line adds a type alias S in the global name space and thus allows you to just write:

void f( S argument ); // struct keyword no longer needed

Note that since both identifier name spaces are different, defining S both in the structs and global spaces is not an error, as it is not redefining the same identifier, but rather creating a different identifier in a different place.

To make the difference clearer:

You can define a function with the same name of the struct as the identifiers are kept in different spaces, but you cannot define a function with the same name as a typedef as those identifiers collide.

In C++, it is slightly different as the rules to locate a symbol have changed subtly. C++ still keeps the two different identifier spaces, but unlike in C, when you only define the symbol within the class identifier space, you are not required to provide the struct/class keyword:

// C++
struct S { 
    int x; 
}; // S defined as a class

void f( S a ); // correct: struct is optional

What changes are the search rules, not where the identifiers are defined. The compiler will search the global identifier table and after S has not been found it will search for S within the class identifiers.

The code presented before behaves in the same way:

typedef struct S { 
    int x; 
} T;

void S() {} // correct [*]

//void T() {} // error: symbol T already defined as an alias to 'struct S'

After the definition of the S function in the second line, the struct S cannot be resolved automatically by the compiler, and to create an object or define an argument of that type you must fall back to including the struct keyword:

// previous code here...
int main() {
    S(); 
    struct S s;
}

@AlexanderVarwijk: You want to typedef to avoid the need to qualify with struct or enum. If the naming conventions you use allow for a function and a type by the same name, the best you can do is review how you name the elements of your program.

@panzi: I cannot think of any downside, on the contrary, it will probably make more sense for other users if the type and the typename have the same name.

This answer explains how the compiler works, and using typedef is a good idea however, it doesn't explain why the struct should be given a name when using the typedef-only form of declaration (2nd example in the question). This is also where I've been at a loss for ~15 years of off-and-on C/C++ programming, and the most important piece of information beyond what I've been taught: just always use typedef; not using it is a pain in the ass.

@SlippD.Thompson The reason to give the struct a name in the tag namespace is so that it could possibly be forward-declared. typedef-only creates an alias to an anonymous struct, and this cannot be forward-declared. stackoverflow.com/a/612350/2757035

c - typedef struct vs struct definitions - Stack Overflow

c struct typedef
Rectangle 27 79

Another difference not pointed out is that giving the struct a name (i.e. struct myStruct) also enables you to provide forward declarations of the struct. So in some other file, you could write:

struct myStruct;
void doit(struct myStruct *ptr);
typedef struct myStruct{
    int one;
    int two;
} myStruct;

This gives you the convenience of the more concise typedef name but still allows you to use the full struct name if you need.

There are ways to do forward declarations with typedef: typedef struct myStruct myStruct;; and then (later): struct myStruct { ... };. You can use it as either struct myStruct or just myStruct after that typedef (but the type is incomplete until that definition).

It's also worth mentioning that C++, despite (conceptually) auto-typedef'ing tags and putting both struct SomeThing and Something in a single 'symbolspace', does make an explicit allowance for a manual typedef SomeThing to redefine to struct SomeThing... where you might otherwise assume this would generate an error about clashing names. Source: stackoverflow.com/a/22386307/2757035 I guess this was done for (slightly futile!) backwards compatibility reasons.

@underscore_d: At the time, people recognized the value in having code which could work equally well as C and C++, and wanted to avoid creating needless barriers to compatibility. Sadly, such thinking is no longer fashionable.

c - typedef struct vs struct definitions - Stack Overflow

c struct typedef
Rectangle 27 66

struct and typedef are two very different things.

The struct keyword is used to define, or to refer to, a structure type. For example, this:

struct foo {
    int n;
};

creates a new type called struct foo. The name foo is a tag; it's meaningful only when it's immediately preceded by the struct keyword, because tags and other identifiers are in distinct name spaces. (This is similar to, but much more restricted than, the C++ concept of namespaces.)

A typedef, in spite of the name, does not define a new type; it merely creates a new name for an existing type. For example, given:

typedef int my_int;

my_int is a new name for int; my_int and int are exactly the same type. Similarly, given the struct definition above, you can write:

typedef struct foo foo;

The type already has a name, struct foo. The typedef declaration gives the same type a new name, foo.

The syntax allows you to combine a struct and typedef into a single declaration:

typedef struct bar {
    int n;
} bar;

This is a common idiom. Now you can refer to this structure type either as struct bar or just as bar.

Note that the typedef name doesn't become visible until the end of the declaration. If the structure contains a pointer to itself, you have use the struct version to refer to it:

typedef struct node {
    int data;
    struct node *next; /* can't use just "node *next" here */
} node;

Some programmers will use distinct identifiers for the struct tag and for the typedef name. In my opinion, there's no good reason for that; using the same name is perfectly legal and makes it clearer that they're the same type. If you must use different identifiers, at least use a consistent convention:

typedef struct node_s {
    /* ... */
} node;

(Personally, I prefer to omit the typedef and refer to the type as struct bar. The typedef save a little typing, but it hides the fact that it's a structure type. If you want the type to be opaque, this can be a good thing. If client code is going to be referring to the member n by name, then it's not opaque; it's visibly a structure, and in my opinion it makes sense to refer to it as a structure. But plenty of smart programmers disagree with me on this point. Be prepared to read and understand code written either way.)

(C++ has different rules. Given a declaration of struct blah, you can refer to the type as just blah, even without a typedef. Using a typedef might make your C code a little more C++-like -- if you think that's a good thing.)

This answer helped me better understand why both C89 libraries and the Linux kernel are more likely to use struct mystruct_t {} rather than typedef struct {} mystruct_t.

c - typedef struct vs struct definitions - Stack Overflow

c struct typedef
Rectangle 27 46

struct myStruct myVariable;

In order to be able to use myStruct myVariable; instead, you can typedef the struct:

typedef struct myStruct someStruct;
someStruct myVariable;

You can combine struct definition and typedefs it in a single statement which declares an anonymous struct and typedefs it.

typedef struct { ... } myStruct;

The last block of code is not equivalent to the previous code. In the last line you are defining a type alias 'myStruct' into an unnamed struct. There are (very) subtle difference among the two versions.

dribeas: I covered this subtle difference in the sentence "...a single statement which declares an anonymous struct and..."

@anthony-arnold: Uhm... I think I already mentioned. In one case there is a type with a name and also an alias, in the other you only have an alias. Where does it matter? Seldomly, but if you have an annonymous type you cannot do struct T x; to declare a variable, or reuse the name for a different type of symbol: typedef struct {} f; void f(); struct f x; fails in the last two statements. Of course, having code like that is not recommended (a type and a function with the same name?)

The accepted answer didn't do a good job contrasting "struct" and "typedef struct", this answer made it clear for me that the "typedef struct" technique is used so C can emulate C++ in order to omit "struct" when using the structure like a data type when passing it.

c - typedef struct vs struct definitions - Stack Overflow

c struct typedef
Rectangle 27 20

In C, the type specifier keywords of structures, unions and enumerations are mandatory, ie you always have to prefix the type's name (its tag) with struct, union or enum when referring to the type.

You can get rid of the keywords by using a typedef, which is a form of information hiding as the actual type of an object will no longer be visible when declaring it.

It is therefore recommended (see eg the Linux kernel coding style guide, Chapter 5) to only do this when you actually want to hide this information and not just to save a few keystrokes.

An example of when you should use a typedef would be an opaque type which is only ever used with corresponding accessor functions/macros.

c - typedef struct vs struct definitions - Stack Overflow

c struct typedef
Rectangle 27 345

typedef is a language construct that associates a name to a type. You use it the same way you would use the original type, for instance

typedef int myinteger;
  typedef char *mystring;
  typedef void (*myfunc)();

using them like

myinteger i;   // is equivalent to    int i;
  mystring s;    // is the same as      char *s;
  myfunc f;      // compile equally as  void (*f)();

As you can see, you could just replace the typedefed name with its definition given above.

The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef 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.

typedef int (*t_somefunc)(int,int);

int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

in the last example, wouldn't just 'square' refer to the same thing i.e pointer to the function instead of using &square.

Question, in your first typedef example you have of the form typedef type alias but with function pointers there only seems to be 2 arguments, typedef type. Is alias defaulted to the name specified in type argument?

@user814628: It is not clear quite what you're asking. With typedef int newname, you are making newname into an alias for int. With typedef int (*func)(int), you are making func into an alias for int (*)(int) a pointer to function taking an int argument and returning an int value.

I guess I'm just confused about the ordering. With typedef int (*func)(int), I understand that func is an alias, just a little confused because the alias is tangled with the type. Going by typedef int INT as an example I would be more of ease if typedef function pointer was of form typedef int(*function)(int) FUNC_1. That way I can see the type and alias in two separate token instead of being meshed into one.

Regarding "Is a function pointer created to store the memory address of a function? Yes, ", no, not in this code. Also, stating that the name introduced by a typedef is a "keyword" is incorrect. And regarding the evaluation "the syntax is appropriate", both the C and C++ language creators disagree, calling it a failed experiment.

c++ - Typedef function pointer? - Stack Overflow

c++ c pointers
Rectangle 27 12

If you use struct without typedef, you'll always have to write

struct mystruct myvar;
mystruct myvar;

If you use the typedef you don't need the struct prefix anymore.

c - typedef struct vs struct definitions - Stack Overflow

c struct typedef
Rectangle 27 344

As Greg Hewgill said, the typedef means you no longer have to write struct all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.

typedef struct {
  int x, y;
} Point;

Point point_new(int x, int y)
{
  Point a;
  a.x = x;
  a.y = y;
  return a;
}

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 typedef, is the case I guess.

Also note that while your example (and mine) omitted naming the struct 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:

typedef struct Point Point;

Point * point_new(int x, int y);

and then provide the struct declaration in the implementation file:

struct Point
{
  int x, y;
};

Point * point_new(int x, int y)
{
  Point *p;
  if((p = malloc(sizeof *p)) != NULL)
  {
    p->x = x;
    p->y = y;
  }
  return 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 GTK+, for instance.

UPDATE Note that there are also highly-regarded C projects where this use of typedef to hide struct is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.

You shouldn't use identifiers with an underscore followed by an uppercase letter, they are reserved (see section 7.1.3 paragraph 1). Although unlikely to be much of a problem, it is technically undefined behaviour when you use them (7.1.3 paragraph 2).

@dreamlax: In case it wasn't clear to others, that's only starting an identifier with an underscore and an upper case that you shouldn't do; you're free to use that in the middle of an identifier.

It's interesting that the example given here (in which the typedef prevents using "struct" "all over the place") is actually longer than the same code without the typedef, since it saves exactly one use of the word "struct". The smidgen of abstraction gained rarely compares favorable with the additional obfuscation.

Interestingly enough, the linux kernel coding guidelines say we should be a lot more conservative about using typedefs (section 5): kernel.org/doc/Documentation/CodingStyle

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

Why should we typedef a struct so often in C? - Stack Overflow

c struct typedef
Rectangle 27 344

As Greg Hewgill said, the typedef means you no longer have to write struct all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.

typedef struct {
  int x, y;
} Point;

Point point_new(int x, int y)
{
  Point a;
  a.x = x;
  a.y = y;
  return a;
}

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 typedef, is the case I guess.

Also note that while your example (and mine) omitted naming the struct 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:

typedef struct Point Point;

Point * point_new(int x, int y);

and then provide the struct declaration in the implementation file:

struct Point
{
  int x, y;
};

Point * point_new(int x, int y)
{
  Point *p;
  if((p = malloc(sizeof *p)) != NULL)
  {
    p->x = x;
    p->y = y;
  }
  return 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 GTK+, for instance.

UPDATE Note that there are also highly-regarded C projects where this use of typedef to hide struct is considered a bad idea, the Linux kernel is probably the most well-known such project. See Chapter 5 of The Linux Kernel CodingStyle document for Linus' angry words. :) My point is that the "should" in the question is perhaps not set in stone, after all.

You shouldn't use identifiers with an underscore followed by an uppercase letter, they are reserved (see section 7.1.3 paragraph 1). Although unlikely to be much of a problem, it is technically undefined behaviour when you use them (7.1.3 paragraph 2).

@dreamlax: In case it wasn't clear to others, that's only starting an identifier with an underscore and an upper case that you shouldn't do; you're free to use that in the middle of an identifier.

It's interesting that the example given here (in which the typedef prevents using "struct" "all over the place") is actually longer than the same code without the typedef, since it saves exactly one use of the word "struct". The smidgen of abstraction gained rarely compares favorable with the additional obfuscation.

Interestingly enough, the linux kernel coding guidelines say we should be a lot more conservative about using typedefs (section 5): kernel.org/doc/Documentation/CodingStyle

Why should we typedef a struct so often in C? - Stack Overflow

c struct typedef
Rectangle 27 163

It's amazing how many people get this wrong. PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs.

Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.

#ifndef FOO_H
#define FOO_H 1

#define FOO_DEF (0xDEADBABE)

struct bar; /* forward declaration, defined in bar.h*/

struct foo {
  struct bar *bar;
};

#endif

With such a definition, not using typedefs, it is possible for a compiland unit to include foo.h to get at the FOO_DEF definition. If it doesn't attempt to dereference the 'bar' member of the foo struct then there will be no need to include the "bar.h" file.

Also, since the namespaces are different between the tag names and the member names, it is possible to write very readable code such as:

struct foo *foo;

printf("foo->bar = %p", foo->bar);

Since the namespaces are separate, there is no conflict in naming variables coincident with their struct tag name.

What's more amazing is that 13 months after this answer is given, I'm the first to upvote it! typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.

Peter van der Linden also makes a case against typedefing structs in his enlightening book "Expert C Programming - Deep C Secrets". The gist is: You WANT to know that something is a struct or union, not HIDE it.

The Linux kernel coding style explicitly forbids typedefing structs. Chapter 5: Typedefs: "It's a mistake to use typedef for structures and pointers." kernel.org/doc/Documentation/CodingStyle

What benefits, exactly, does typing "struct" over and over again provide? And speaking of pollution, why would you want to have a struct and a function/variable/typedef with the same name in a global namespace (unless it's a typedef for that same function)? The safe pattern is to use typedef struct X { ... } X. That way you can use the short form X to address the struct anywhere the definition is available, but can still forward-declare and use struct X when desired.

I personal very rarely if ever use typedef, I wouldn't say other people shouldn't use it, it just not my style. I like to see a struct before a variable type so I know straight away its a struct. The easier to type argument is a bit lame, having variable that are a single letter is also easier to type, also with auto completions how hard is it to type struct nowadays anywhere.

Why should we typedef a struct so often in C? - Stack Overflow

c struct typedef
Rectangle 27 163

It's amazing how many people get this wrong. PLEASE don't typedef structs in C, it needlessly pollutes the global namespace which is typically very polluted already in large C programs.

Also, typedef'd structs without a tag name are a major cause of needless imposition of ordering relationships among header files.

#ifndef FOO_H
#define FOO_H 1

#define FOO_DEF (0xDEADBABE)

struct bar; /* forward declaration, defined in bar.h*/

struct foo {
  struct bar *bar;
};

#endif

With such a definition, not using typedefs, it is possible for a compiland unit to include foo.h to get at the FOO_DEF definition. If it doesn't attempt to dereference the 'bar' member of the foo struct then there will be no need to include the "bar.h" file.

Also, since the namespaces are different between the tag names and the member names, it is possible to write very readable code such as:

struct foo *foo;

printf("foo->bar = %p", foo->bar);

Since the namespaces are separate, there is no conflict in naming variables coincident with their struct tag name.

What's more amazing is that 13 months after this answer is given, I'm the first to upvote it! typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.

Peter van der Linden also makes a case against typedefing structs in his enlightening book "Expert C Programming - Deep C Secrets". The gist is: You WANT to know that something is a struct or union, not HIDE it.

The Linux kernel coding style explicitly forbids typedefing structs. Chapter 5: Typedefs: "It's a mistake to use typedef for structures and pointers." kernel.org/doc/Documentation/CodingStyle

What benefits, exactly, does typing "struct" over and over again provide? And speaking of pollution, why would you want to have a struct and a function/variable/typedef with the same name in a global namespace (unless it's a typedef for that same function)? The safe pattern is to use typedef struct X { ... } X. That way you can use the short form X to address the struct anywhere the definition is available, but can still forward-declare and use struct X when desired.

I personal very rarely if ever use typedef, I wouldn't say other people shouldn't use it, it just not my style. I like to see a struct before a variable type so I know straight away its a struct. The easier to type argument is a bit lame, having variable that are a single letter is also easier to type, also with auto completions how hard is it to type struct nowadays anywhere.

Why should we typedef a struct so often in C? - Stack Overflow

c struct typedef
Rectangle 27 30

It's a typedef to a function type. The intent is to use it for function pointers, but in this case the syntax to use it would be:

int bar(void);

fc_name* foo = bar; /* Note the * */

Update: As mentioned in the comments to Jonathan Leffler's answer, the typedef can be used to declare functions. One use could be for declaring a set of callback functions:

typedef int (callback)(int, void*);

callback onFoo;
callback onBar;
callback onBaz;
callback onQux;

+1: Ah - so that's how it gets to be useful! I've demonstrated that you're correct - but only once you showed me how. We live, we learn; SO rocks.

c - What does a typedef with parenthesis like "typedef int (f)(void)" ...

c typedef
Rectangle 27 108

The C language rules for naming structs are a little eccentric, but they're pretty harmless. However, when extended to classes in C++, those same rules open little cracks for bugs to crawl through.

In C, the name s appearing in

struct s
    {
    ...
    };

is a tag. A tag name is not a type name. Given the definition above, declarations such as

s x;    /* error in C */
s *p;   /* error in C */

are errors in C. You must write them as

struct s x;     /* OK */
struct s *p;    /* OK */

The names of unions and enumerations are also tags rather than types.

In C, tags are distinct from all other names (for functions, types, variables, and enumeration constants). C compilers maintain tags in a symbol table that's conceptually if not physically separate from the table that holds all other names. Thus, it is possible for a C program to have both a tag and an another name with the same spelling in the same scope. For example,

struct s s;

is a valid declaration which declares variable s of type struct s. It may not be good practice, but C compilers must accept it. I have never seen a rationale for why C was designed this way. I have always thought it was a mistake, but there it is.

Many programmers (including yours truly) prefer to think of struct names as type names, so they define an alias for the tag using a typedef. For example, defining

struct s
    {
    ...
    };
typedef struct s S;

lets you use S in place of struct s, as in

S x;
S *p;

A program cannot use S as the name of both a type and a variable (or function or enumeration constant):

S S;    // error

The tag name in a struct, union, or enum definition is optional. Many programmers fold the struct definition into the typedef and dispense with the tag altogether, as in:

typedef struct
    {
    ...
    } S;

The linked article also has a discussion about how the C++ behavior of not requireing a typedef can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.

Thanks for clearly explaining the whole issue. As a C++ guy I didn't even know about these tags.

One example of where the tag name is the same as a non-tag name is in (POSIX or Unix) program with the int stat(const char *restrict path, struct stat *restrict buf) function. There you have a function stat in the ordinary name space and struct stat in the tag name space.

your statement , S S; // error .... IS WRONG It works well. I mean your statement that "we cant have same name for typedef tag and var" is WRONG... pls check

Why should we typedef a struct so often in C? - Stack Overflow

c struct typedef
Rectangle 27 108

The C language rules for naming structs are a little eccentric, but they're pretty harmless. However, when extended to classes in C++, those same rules open little cracks for bugs to crawl through.

In C, the name s appearing in

struct s
    {
    ...
    };

is a tag. A tag name is not a type name. Given the definition above, declarations such as

s x;    /* error in C */
s *p;   /* error in C */

are errors in C. You must write them as

struct s x;     /* OK */
struct s *p;    /* OK */

The names of unions and enumerations are also tags rather than types.

In C, tags are distinct from all other names (for functions, types, variables, and enumeration constants). C compilers maintain tags in a symbol table that's conceptually if not physically separate from the table that holds all other names. Thus, it is possible for a C program to have both a tag and an another name with the same spelling in the same scope. For example,

struct s s;

is a valid declaration which declares variable s of type struct s. It may not be good practice, but C compilers must accept it. I have never seen a rationale for why C was designed this way. I have always thought it was a mistake, but there it is.

Many programmers (including yours truly) prefer to think of struct names as type names, so they define an alias for the tag using a typedef. For example, defining

struct s
    {
    ...
    };
typedef struct s S;

lets you use S in place of struct s, as in

S x;
S *p;

A program cannot use S as the name of both a type and a variable (or function or enumeration constant):

S S;    // error

The tag name in a struct, union, or enum definition is optional. Many programmers fold the struct definition into the typedef and dispense with the tag altogether, as in:

typedef struct
    {
    ...
    } S;

The linked article also has a discussion about how the C++ behavior of not requireing a typedef can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.

Thanks for clearly explaining the whole issue. As a C++ guy I didn't even know about these tags.

One example of where the tag name is the same as a non-tag name is in (POSIX or Unix) program with the int stat(const char *restrict path, struct stat *restrict buf) function. There you have a function stat in the ordinary name space and struct stat in the tag name space.

your statement , S S; // error .... IS WRONG It works well. I mean your statement that "we cant have same name for typedef tag and var" is WRONG... pls check

Why should we typedef a struct so often in C? - Stack Overflow

c struct typedef
Rectangle 27 6

The typedef uses the same syntax for declaring types as would normally be used for declaring values.

int
myInt
int myInt;

If we want to declare a type called myIntType to be an int, we simply add typedef:

typedef int myIntType;

We can declare a function myFunc, as follows:

int myFunc(int a, int b);

Which tells the compiler that there is an actual function with that name and signature that we can call.

We can also declare a function type myFuncType by doing:

typedef int myFuncType(int a, int b);
myFuncType myFunc;

Which is equivalent to the previous declaration of myFunc (although this form would rarely be used).

A function is not a conventional value; it represents a block of code with an entry point address. Function declarations like those above are implicitly extern; they tell the compiler that the named thing exists somewhere else. However, you can take the address of a function, which is called a function pointer. A function pointer can point to any function with the correct signature. A pointer is declared by prefixing the name of the type/value with a *, so, we might try:

int *myFuncPtr(int a, int b);

But this would be incorrect because the * binds more tightly with the int, so we have declared that myFuncPtr is a function that returns a pointer to an int. We must put parens around the pointer and name to change the binding order:

int (*myFuncPtr)(int a, int b);
typedef
typedef int (*myFuncPtrType)(int a, int b);

In the declaration of myInt above, the compiler allocated some memory for the variable. However, if we were writing some code in a different compilation unit, and wanted to reference myInt, we would need to declare it as extern (in the referencing compilation unit) so that we reference the same memory. Without the extern, the compiler would allocate a second myInt, which would result in a linker error (actually that's not quite true because C allows tentative definitions, which you shouldn't use).

As noted above, functions are not normal values, and are always implicitly extern. However, function pointers are normal values, and need the extern if you are trying to reference a global function pointer from a separate compilation unit.

Normally, you would put externs for your global variables (and functions) into a header file. You would then include the header into the compilation units that contain the definitions of those variables and functions so that the compiler can make sure the types match.

About the extern keyword. If there's a problem of allocating the same variable twice why just not use the #ifndef XXX #define XXX <code> #endif directives ?

You could use an ifdef to make the extern for a variable appear in all but one compilation unit, but you'll also have to ifdef any initializer. Better to just put an extern in a header, and a definition in a .c file.

c - typedef function pointers and extern keyword - Stack Overflow

c function-pointers typedef extern
Rectangle 27 5

The difference comes in when you use the struct.

The first way you have to do:

struct myStruct aName;

The second way allows you to remove the keyword struct.

myStruct aName;

c - typedef struct vs struct definitions - Stack Overflow

c struct typedef
Rectangle 27 15

The first parentheses are superfluous - it is equivalent to:

typedef int fc_name(void);

This means that fc_name is an alias for a function type that takes no arguments and returns an int. It isn't directly all that useful, though you can declare, for example, the rand() function using:

fc_name rand;

You cannot use the typedef in a function definition.

typedef int (*fc_name)(void);

This code shows that the typedefs without the asterisk are not function pointers (addressing a now-deleted alternative answer):

gcc -Wextra -Wall -pedantic -c -O x.c
x.c:10:1: error: function x is initialized like a variable
x.c:11:1: error: function y is initialized like a variable

And this code demonstrates that you can indeed use fc_name *var = funcname; as suggested by jamesdlin:

static int function(void)
{
    return 0;
}

typedef int   fc_name1 (void);
typedef int  (fc_name2)(void);
typedef int (*fc_name3)(void);

fc_name1  x_0 = function;
fc_name1 *x_1 = function;
fc_name2  y_0 = function;    // Damn Bessel functions - and no <math.h>
fc_name2 *y_1 = function;    // Damn Bessel functions - and no <math.h>
fc_name3  z   = function;
x.c:12:11: warning: conflicting types for built-in function y0
x.c:13:11: warning: built-in function y1 declared as non-function

And, building on the comment from schot:

static int function(void)
{
    return 0;
}

typedef int   fc_name1 (void);
typedef int  (fc_name2)(void);
typedef int (*fc_name3)(void);

fc_name1  x_0 = function;   // Error
fc_name1 *x_1 = function;   // x_1 is a pointer to function
fc_name1  x_2;              // Declare int x_2(void);
fc_name1 *x_3 = x_2;        // Declare x_3 initialized with x_2

fc_name2  y_0 = function;   // Damn Bessel functions - and no <math.h>
fc_name2 *y_1 = function;   // Damn Bessel functions - and no <math.h>
fc_name1  y_2;              // Declare int y_2(void);
fc_name1 *y_3 = x_2;        // Declare y_3 initialized with y_2

fc_name3  z   = function;

Interesting - the dark corners of C are murky indeed.

Some people prefer the typedef to be of the function signature pre-pointer-taking. That shifts the "explictness" of taking a pointer to the declaration of each function pointer. It's a matter of style, I think.

You can also use a function typedef for a function declaration (prototype), but not for a definition. But this is not very useful, except for obfuscation.

@schot: Neat, I didn't know it could be used for function declarations. I actually do think that is kind of useful for declaring a set of callback functions; previously I was using a preprocessor macro to simplify that.

Can we remove the jamesdlin example, since the schot example is a superset?

c - What does a typedef with parenthesis like "typedef int (f)(void)" ...

c typedef
Rectangle 27 4

You can't use forward declaration with the typedef struct.

The struct itself is an anonymous type, so you don't have an actual name to forward declare.

typedef struct{
    int one;
    int two;
} myStruct;

A forward declaration like this won't work:

struct myStruct; //forward declaration fails

void blah(myStruct* pStruct);

//error C2371: 'myStruct' : redefinition; different basic types

c - typedef struct vs struct definitions - Stack Overflow

c struct typedef
Rectangle 27 49

Using a typedef avoids having to write struct every time you declare a variable of that type:

struct elem
{
 int i;
 char k;
};
elem user; // compile error!
struct elem user; // this is correct

ok we are not having that problem in C++. So why dont anybody remove that glitch from the C's compiler and make it the same as in C++.ok C++ is having some different application areas and so it is having the advanced features.but can we not inherit some of them in C without changing the original C?

Manoj, the tag name ("struct foo") is necessary when you need to define a struct that references itself. e.g. the "next" pointer in a linked list. More to the point, the compiler implements the standard, and that's what the standard says to do.

It's not a glitch in the C compiler, it's part of the design. They changed that for C++, which I think makes things easier, but that doesn't mean C's behavior is wrong.

unfortunately many 'programmers' define a struct then typedef it with some 'unrelated' name (like struct myStruct ...; typedef struct myStruct susan*; In almost all instances a typedef leads to nothing but cluttering the code, hiding the actual definition of a variable/parameter, and mis-leads everyone, including the original writer of the code.

Why should we typedef a struct so often in C? - Stack Overflow

c struct typedef