Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are `typedef` and `struct` inside of a function standard in C?

Tags:

I used some code like this:

void A() {     typedef struct B B;     struct B     {      };      B b; }; 

typedef and struct definition inside a function. It compiled with Clang, but I want to know (1) whether they are part of standard or not. And about (2) whether they are limited to be recognized in function scope only.

like image 840
eonil Avatar asked Apr 08 '11 05:04

eonil


People also ask

Can you have a struct inside a function?

Structures can be passed as function arguments like all other data types. We can pass individual members of a structure, an entire structure, or, a pointer to structure to a function. Like all other data types, a structure or a structure member or a pointer to a structure can be returned by a function.

Should you use typedef with struct?

In general, a pointer, or a struct that has elements that can reasonably be directly accessed should never be a typedef.

What is struct and typedef in C?

The C language contains the typedef keyword to allow users to provide alternative names for the primitive (e.g.,​ int) and user-defined​ (e.g struct) data types. Remember, this keyword adds a new name for some existing data type but does not create a new type.

Can struct be defined inside class?

Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.


1 Answers

Yes, the standard allows this, and yes, the name you create this way is only visible inside the function (i.e., it has local scope, just like when you define int i;, i has local scope).

It's more common, however to do it something like this:

typedef struct {      /* ... */  } B; B b; 
like image 182
Jerry Coffin Avatar answered Oct 04 '22 19:10

Jerry Coffin