Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same name structure with different definition in C

Is it allowed to use same name structure with different definitions in 2 different c files in the same project. For eg.

File1.c

typedef struct
{
    unsigned int unVar;             

} abc;

File2.c

typedef struct
{
    int var;
} abc;

abc is used in both the files. When i compile these file as part of same project there are no errors, but i want to understand whether this is correct usage.

like image 602
Anuj Priyadarshi Avatar asked Jan 27 '16 10:01

Anuj Priyadarshi


People also ask

Can two elements within a structure have the same name C?

Yes you can use the variable with same name in different structure.

Can a structure have different data types?

A struct is also a collection of data items, except with a struct the data items can have different data types, and the individual fields within the struct are accessed by name instead of an integer index.

Can struct and variable have same name?

This question already has an answer here:Yes, that is perfectly fine.

How many ways can you define a structure in C?

There are two ways to declare structure variable: By struct keyword within main() function.


2 Answers

6.7.2.1 Structure and union specifiers

  1. The presence of a struct-declaration-list in a struct-or-union-specifier declares a new type, within a translation unit.

Types are defined only within a translation unit, a .c file in this case.

There is no problem with defining two types with the same name in two different translation units.

However those two types are not compatible unless they follow the rules described in 6.2.7., p1. The types you defined are not compatible.

like image 104
2501 Avatar answered Sep 18 '22 21:09

2501


This is type definition. It is local for each .c file and there is no reason to get error. Definitions have to be made in header files and then you will not have such problem.

like image 44
i486 Avatar answered Sep 20 '22 21:09

i486