Enumeration Scope - c

If I have enums like:
enum EnumA
{
stuffA = 0
};
enum enumAA
{
stuffA = 1
};
What happens here when you refer to stuffA? I thought you would refer to them like EnumA.stuffA and EnumB.stuffA as in Java, but that doesn't seem to be the case in C.

enums don't introduce new scope.
In your example, the second enum wouldn't compile due to the stuffA name clash.
To avoid name clashes, it is a common practice to give the elements of an enum a common prefix. Different prefixes would be used for different enums:
enum EnumA
{
EA_stuffA = 0
};
enum EnumAA
{
EAA_stuffA = 1
};

The enumeration constants are in the global name space (more precisely, the ordinary identifiers name space, contrasted with the labels, tags, and structure/union member namespaces), so you get a compilation error on the second stuffA.
You cannot use two different values for the same enumeration name (nor the same value specified twice) in a single translation unit.

As the others already said enumeration constants must be unique in the actual scope where they are defined. But with them as with other identifiers it is allowed to redefine them in another scope. Eg.
enum EnumA
{
stuffA = 0
};
void func(void) {
enum enumAA
{
stuffA = 1
};
// do something
}
would be fine. But such redefinitions in different scopes are often frowned upon and should be well documented, otherwise you will quickly loose yourself and others.

As mentioned, this won't compile because stuffA is defined twice. Enum values are simply referred to by the enumeration (that is "stuffA" rather than EnumA.stuffA). You can even use them on types that aren't enums (such as integers). Enums are sometimes used this way with ints, similar to the way one would #define constants.

This answer shows how the rules of C 2018 preclude the same identifier from being used as a member of two different enumerations. It is a language-lawyer view, intended to show how this requirement arises out of the language of the standard.
6.2.3, “Name spaces of identifiers,” tells us:
If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers, as follows:
…
— all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
Thus, all enumerator constants and ordinary declarators exist in one name space. (The name spaces omitted above are for labels [for goto statements]; tags of structures, unions, and enumerations [the name after a struct, as in struct foo]; and members of structures or unions [each has its own name space]).
6.7, "Declarations," tells us in paragraph 5 that:
A definition of an identifier is a declaration for that identifier that:
…
for an enumeration constant, is the (only) declaration of the identifier;
…
So the standard indicates that there is only one definition of an enumeration constant. Additionally, 6.2.1, “Scopes of identifiers,” tells us in paragraph 1:
An identifier can denote an object; a function; a tag or a member of a structure, union, or enumeration; a typedef name; a label name; a macro name; or a macro parameter. The same identifier can denote different entities at different points in the program. A member of an enumeration is called an enumeration constant.
Observe that this tells that if foo identifies an enumeration constant, it identifies a member of an enumeration—it is a particular member of a particular enumeration. It cannot identify both a member of enum A and a member of enum B. Therefore, if we had the code:
enum A { foo = 1 };
enum B { foo = 1 };
at the point where foo appears the second time, it is an identifier for foo in enum A, and therefore it cannot be a member of enum B.
(The sentence about an identifier denoting different entities at different points is introducing the concept of scope. Further paragraphs in that clause explain the concept of scope and the four kinds of scope: function, file, block, and function prototype. These do not affect the above analysis because the code above is within one scope.)

Depending on where you declare these enums, you could also declare new scopes using the namespace keyword.
NOTE: I wouldn't recommend doing this, I'm just noting that it's possible.
Instead, it would be better to use a prefix as noted in the other examples.
namespace EnumA
{
enum EnumA_e
{
stuffA = 0
};
};
namespace EnumAA
{
enum enumAA_e
{
stuffA = 1
};
};

Related

c - How to initialize a constant structure

I would like to avoid having constant values hardcoded in my C files, so I was wondering if i had a way to intialize a struct constant directly in a header file to use it everywhere i included the header file? (in the way #define works for constants with simple types)
All answers i found so far have been:
const int var = 5; /*in header*/
which only works in C++ (not C)
Using a C file to initialize the constant which is not what i'm looking for
The best answer to this post: How do I use extern to share variables between source files?
which seems a bit complicated...
Thanks in advance for the answers or help you can bring me! :)
EDIT : I am adding more details to my question.
I want to stock hardware parameters of the system i use in a structure :
struct parameters_Component1 {
int const1 = 5;
double const2 = 7,847
}
struct parameters_Component2 {
int const1 = 6;
double const2 = 9,3343
}
or a struct equivalent to
#define myConst 5;
I want to have those constants values regrouped in a header file i can access and modify rather than in my C code for organisation purpose
I would like to avoid having constant values hardcoded in my C files,
so I was wondering if i had a way to intialize a struct constant
directly in a header file to use it everywhere i included the header
file? (in the way #define works for constants with simple types)
You first need to get a clearer idea of what you mean, relative to the semantics of the C language. In C terminology, constants are syntactic constructs that represent specific values in source code. They do not have their own associated storage, and they are available only for built-in types. What you want is not a "constant" in this sense, or at least, C does not provide for structure constants in that sense. This has nothing whatever to do with the const type qualifier.
There are several things that C does offer in this general area:
structure initializers, which work similarly to constants for initializing objects of structure types;
objects having unmodifiable (const) structure type; and
compound literals of structure type.
Initializers
As their name suggests, initializers can be used in object declarations to initialize the declared objects. They are not values per se, however, so they cannot be assigned to objects post-declaration or otherwise used where an expression is required. You can define a macro that expands to an initializer, and this is sometimes done. Example
header1.h
struct my_struct { int x; int y; };
#define MY_STRUCT_INITIALIZER { .x = 0, .y = 0 }
code1.c
// ...
// This is initialization, not assignment:
struct my_struct s = MY_STRUCT_INITIALIZER;
An initializer has no storage of its own.
Unmodifiable objects
As in C++, any data type can be const-qualified to produce a type for objects that cannot be modified. Such objects thus must take their value from an initializer, or be function parameters, or else be declared in a way that causes them to be default-initialized, for being unmodifiable means there is no other way to define their values. Unlike an initializer, these are bona fide objects with data types and associated storage, and they can be used in any expression compatible with their type. Similarly, the identifiers associated with const objects must satisfy C's rules for scope and linkage, just like other identifiers. In particular, although there can be multiple declarations of any object with external (or internal) linkage, there can be only one definition of each.
External objects
If you want to use the same object "everywhere", then that implies external linkage. Good style then calls for that object to be declared in a header, but it cannot be defined in a header because that would result in duplicate definitions if the header were included in more than one translation unit. This is well supported by C via the following idiom:
header2.h
struct my_struct { int x; int y; };
// a declaration:
extern const struct my_struct shared_struct; // NOTE: explicit "extern" and no initializer
my_struct_stuff.c
#include "header2.h"
// a definition:
const struct my_struct shared_struct = { .x = 1, .y = 2 };
other.c
#include "header2.h"
// no definition of shared_struct here
// ...
int x = shared_struct.x;
int y = shared_struct.y;
// ...
This affords a single unmodifiable object, shared among as many translation units as you like, but it does not satisfy your criterion of keeping everything in a header. It is possible to play conditional compilation games to get the definition to appear lexically in the header, but you still need exactly one designated source file that makes provision for providing the definition. (Details left as an exercise.)
Internal objects
Alternatively, if it is sufficient to use an equivalent but different object in each translation unit, then your header can define an unmodifiable object whose identifier has internal linkage. Each translation unit that includes the header will then have its own, independent copy of the object:
header3.h
struct my_struct { int x; int y; };
static const struct my_struct local_struct = { .x = 1, .y = 2 };
This satisfies your criterion of keeping everything in the header file, but you may have reason, even apart from storage-use considerations, for wanting to provide the same object to each translation unit, and this does not achieve that objective. Also, your compiler may emit warnings for translation units that include the header but do not access local_struct.
Compound literals
C also has compound literals of structure types, which are analogous in some ways to string literals. They represent bona fide objects, with data types and storage, and have a lexical form that conveys the objects' values directly. Compound literals may have const-qualified types, but they are not const by default, and in general, it is acceptable to modify an object corresponding to a compound literal in any way permitted by its type. Also, unlike string literals, compound literals do not necessarily have static storage duration. Furthermore, each appearance of a compound literal represents a separate object.
Lexically, a compound literal resembles a cast operator for a structure, union, or array type, applied to a corresponding initializer for an object of that type:
header4.h
struct my_struct { int x; int y; };
#define MY_STRUCT_LITERAL ((struct my_struct) { .x = 42, .y = 42 })
/* or:
#define MY_STRUCT_LITERAL ((const struct my_struct) { .x = 42, .y = 42 })
*/
Macros expanding to compound literals can be defined in headers, as shown, but it is important to understand that each appearance of such a macro will correspond to a separate object. Under some circumstances, the compiler might optimize out reserving any actual storage, but a compound literal is not a "constant" in the same sense as an integer or floating constant.
Overall
Your main available alternatives are presented above. It's unclear to me what or how much value you place on having the values appear lexically in a header file, as opposed to, say, in an accompanying for-purpose source file representing a translation unit. It's also unclear to me what relative importance you attribute to minimizing storage requirements for these data, or whether the object identities of the structures need to be significant. And inasmuch as you raised C++ in comparison, I should not overlook the fact that compound literals are a C feature that C++ does not provide. These are the considerations you should bear in mind in choosing among those possibilities.
Or you could also consider whether you really want to arrange the data in actual structure objects at all. I have focused on that because it's what you asked about, but there are macro-based options that would allow you to tabulate your data in a header, in fairly compact form, and use function-like macros instead of structure-access syntax to access them.

Namespaces in C formal definition

I'm reading the N1570 Standard and have a problem to understand the wording of the name space definition. Here is it:
1 If more than one declaration of a particular identifier is visible
at any point in a translation unit, the syntactic context
disambiguates uses that refer to different entities. Thus, there are
separate name spaces for various categories of identifiers, as
follows:
— label names (disambiguated by the syntax of the label
declaration and use);
— the tags of structures, unions, and
enumerations (disambiguated by following any32) of the keywords
struct, union, or enum);
— the members of structures or unions; each
structure or union has a separate name space for its members
(disambiguated by the type of the expression used to access the member
via the . or -> operator);
— all other identifiers, called ordinary
identifiers (declared in ordinary declarators or as enumeration
constants).
32) There is only one name space for tags even though three are possible.
Here they are talking about in case of more than 1 declaration of particular identifiers is visible. Now words something like "To access an identifier one shall specify its namespace" or "To access an identifier in a specific namespace...".
Let me show an example first (this is strictly for understanding purpose, dont write code like this, ever)
#include <stdio.h>
int main(void)
{
int here = 0; //.......................ordinary identifier
struct here { //.......................structure tag
int here; //.......................member of a structure
} there;
here: //......... a label name
here++;
printf("Inside here\n");
there.here = here; //...........no conflict, both are in separate namespace
if (here > 2) {
return 0;
}
else
goto here; //......... a label name
printf("Hello, world!\n"); // control does not reach here..intentionally :)
return 0;
}
You see usage of identifier here. They belong to separate namespace(s) according to the rule, hence this program is fine.
However, say, for example, you change the structure variable name, from there to here, and you'll see a conflict, as then, there would be two separate declaration of same identifier (ordinary identifier) in the same namespace.

Why doesn't the compiler give a conflicting error?

In following code, I have declared a structure member variable as a same name of structure name.
struct st
{
int st;
};
int main()
{
struct st t;
t.st = 7;
return 0;
}
I wonder, it's working fine on GCC compiler and doesn't give a conflict error.
So,
How does the compiler know structure name and variable name?
What mechanism compiler internally use?
Yes, it's valid. The struct tag and the struct members are in different namespace.
C11, 6.2.3 Name spaces of identifiers:
If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers, as follows:
label names (disambiguated by the syntax of the label declaration and use);
the tags of structures, unions, and enumerations (disambiguated by following any32) of the keywords struct, union, or enum);
the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the . or -> operator);
all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
The name of the structure type is struct st. Not just st, so there's no conflict at all.

Why does GCC define unary operator '&&' instead of just using '&'?

As discussed in this question, GCC defines nonstandard unary operator && to take the address of a label.
Why does it define a new operator, instead of using the existing semantics of the & operator, and/or the semantics of functions (where foo and &foo both yield the address of the function foo())?
Label names do not interfere with other identifiers, because they are only used in gotos. A variable and a label can have the same name, and in standard C and C++ it's always clear from the context what is meant. So this is perfectly valid:
name:
int name;
name = 4; // refers to the variable
goto name; // refers to the label
The distinction between & and && is thus needed so the compiler knows what kind of name to expect:
&name; // refers to the variable
&&name; // refers to the label
GCC added this extension to be used in initializing a static array that will serve as a jump table:
static void *array[] = { &&foo, &&bar, &&hack };
Where foo, bar and hack are labels. Then a label can be selected with indexing, like this:
goto *array[i];
Standard says that
C11: 6.2.1 Scopes of identifiers (p1):
An identifier can denote an object; a function; a tag or a member of a structure, union, or enumeration; a typedef name; a label name; a macro name; or a macro parameter.
Further it says in section 6.2.3:
If more than one declaration of a particular identifier is visible at any point in a translation unit, the syntactic context disambiguates uses that refer to different entities. Thus, there are separate name spaces for various categories of identifiers, as follows:
— label names (disambiguated by the syntax of the label declaration and use);
— the tags of structures, unions, and enumerations (disambiguated by following any32) of the keywords struct, union, or enum);
— the members of structures or unions; each structure or union has a separate name space for its members (disambiguated by the type of the expression used to access the member via the . or -> operator);
— all other identifiers, called ordinary identifiers (declared in ordinary declarators or as enumeration constants).
This means that an object and a label can be denoted by same identifier. At this point, to let the compiler know that the address of foo is the address of a label, not the address of an object foo (if exists), GCC defined && operator for address of label.

Can enums have limited scope if defined inside a struct in c

I want to know if an enum can be limited in how it is access by putting it inside a struct. I know that this would work in C++ (that's where I got the idea), but I don't know if it will work in c. So, for example, if I have two different structs
struct SaticArrayA
{
enum { MAX_SIZE = 10 };
int array[MAX_SIZE];
};
struct SaticArrayB
{
enum { MAX_SIZE = 20 };
int array[MAX_SIZE];
};
Will this even close to compile? Basically, I want to do what I would do in C++ and give myself a common naming convention across "classes" so that I can ask any array what it's size is, etc.
(p.s. I'm essentially trying to give myself a nicer static array in c that won't lose size information (by decaying to a pointer) the second I try to pass it to another scope).
It will not compile,
you didn't give the enumerator a tag
enum { MAX_SIZE = 10 } name ;
and you declared two enumerator constants with the same name
MAX_SIZE
C11 standard on scopes of indentifiers:
6.2.1. p7 Structure, union, and enumeration tags have scope that begins just after the appearance of
the tag in a type specifier that declares the tag. Each enumeration constant has scope that
begins just after the appearance of its defining enumerator in an enumerator list. Any
other identifier has scope that begins just after the completion of its declarator
This means that your first enumerator has a scope in the entire file from the line it is declared onward.
The second enum declaration with the same name is not correct and should not compile.
It doesn't matter where enums are being declared for this rule, struct or not, once declared they are in file scope from that point on.

Resources