Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local struct in c

Tags:

c

If a struct is only used in one function, can I declare it in that function? Can I do this:

int func()
{
    struct {
        int a, b;
    } s;

    s.a=5;

    return s.a;
}

gcc choked on it, but it emitted a very weird looking error that I couldn't understand instead of saying "Sorry, you can't do that".

like image 320
Baruch Avatar asked Jun 13 '12 14:06

Baruch


People also ask

What is local structure in C?

Structure is a collection of different datatype variables, grouped together under a single name. General form of structure declaration. The structure declaration is as follows − struct tagname{ datatype member1; datatype member2; datatype member n; }; Here, struct is the keyword.

What is the difference between local and global structure?

While the global structure defines the outer shape of the process dataset, the local structure provides its inner organization.

What is a global structure in C?

You can define structure globally and locally. If the structure is global then it must be placed above all the functions, so that any function can use it. On the other hand, if a structure is defined inside a function then only that function can use the structure.

What is struct library in C?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).


1 Answers

This is perfectly valid C89/C99/C11 code, this a structure with no tag and the object has block scope. Check C99 6.7.2.3p6 to see the identifier for the tag is optional.

like image 80
ouah Avatar answered Oct 29 '22 15:10

ouah