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.
Related
First, from this:
static struct foo1 { //private struct, just for this file
int a;
};
int main (void) {
struct foo1 a = {10};
return 0;
}
question number 1
I will get warning:
warning: useless storage class specifier in empty declaration
};
What does it mean? Why is static "useless storage class specifier"? In other context (static local var in function, or global static, which I wanted to apply for the struct foo1, it would work).
question number 2
#include <stdbool.h>
static struct s_t{ //private struct (for this file only)
static bool is_there = false; // defaul (pre-defined) value for all instances
int value;
};
int main (void) {}
Why is not possible to have static, predefined value for all vars of type struct s_t in c? I just wanted to simulate the same functionality as is in function static local var -> preserve value across multiple calls, in that sense, I wanted have one member (bool is_there in this case) that preserve value across each var of type struct foo1 (instance of it). So why it is not possible?
question number 3
Also, can someone explain the error (in more general sense) from it:
error: expected specifier-qualifier-list before ‘static’
EDIT:
from comments, I do not really understand the concept of storage class, I know only from asm, there is data/text/bss segments, so does it mean static var has address in read-only part of memory? Or what is the concept of storage class in c related to asm?
Because static struct foo1 { ... is just a struct definition, not a variable. You should add static when you declare the instance of the struct. I prefer this style:
typedef struct {
int a;
}foo_t;
static foo_t a = {10};
Because C simply doesn't have static member variables like C++ does. In C, it's pretty useless to add storage- or type specifiers to a single struct member. Put it on the allocated variables instead.
TL;DR it's just not making any sense of your syntax since you can't have static there. Unless you are terribly interested about language grammar, there's nothing else to it.
static is a storage-class specifier and const etc are type qualifiers and int etc is a type specifier. The term specifier-qualifier list comes from formal C grammar of structs, which isn't terribly interesting to read unless you are making a compiler. When declaring a struct member you have two options (C17 6.7.2.1):
specifier-qualifier-list:
type-specifier specifier-qualifier-list(opt)
type-qualifier specifier-qualifier-list(opt)
static doesn't fit the bill of either, being a storage-class specifier, so the compiler is saying "what! this is not a specifier-qualifier list where I expected to find one, where is it?"
(And yeah it's recursive, so you can have multiple of type-specifier or type-qualifier such as const long const const int value;. Because C stands for Crazy.)
because struct is like a type or an object, when you declare a static member in C, it would be like:
static int a = 0;
In this case "int" is like the struct type you declared, so if you want to create a struct static member just do like this:
static s_t a;
static struct foo1 { //private struct, just for this file
int a;
};
The static declaration specifier only applies to object or function declarations, not type definitions. All you're doing in that statement is creating the struct foo1 type. Had you written something like
static struct foo1 {
int a;
} foo;
Then the object foo would be declared static.
If you declare the type within the .c file, it will only be visible within that .c file. The only way to make the type visible to multiple .c files is to declare it in a header and #include that header in each file that needs it.
Why is not possible to have static, predefined value for all vars of type struct s_t in c?
Because C struct types are simply not that sophisticated - they're just a way to define a data item with multiple attributes. The language doesn't provide any way to have members that are common across all instances of the type.
Remember that C is a product of the early 1970s and was originally developed to implement the Unix operating system - it was designed to be small, portable, and fast. A lot's been added to it over the last 40-some-odd years, but nothing that really changes the core philosophy of the language.
Well, its quite evident that you will get the warning. The reason is simple! You are trying to assign a Storage Class to the struct definition.
However, storage classes are applicable to variable declarations. Therefore, you are getting the prompt.
If you still wish to employ the static storage class, then you can do so with any variable, preferably, any instance of the 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.
Doing practice questions for a 1st Year Programming "101" exam. Trying something and I'm not sure its possible.
Q. Give a type definition suitable for representing the assignment marks for 10 students and initialised all marks to zero.
As I interpret that the examiner wants the def and initialisation to be done together. Otherwise Id just make a struct and initialize it after.
typedef int foobar[10]; //is accepted but is not initialised
typedef int foobar[10] = {0}; //Error " , expected"
typedef int foobar[10] = {0,0,0,0,0,0,0,0,0,0}; //Error " , expected"
Is it possible to do what I'm attempting or does initialization have to be done separately?
NB: All the previous questions I could find related to structs where Im specifically looking at an array of int.
Initialize typedef of int arrray within definition?
...
Give a type definition suitable for representing the assignment marks for 10 students and initialised all marks to zero.
The title and the question make no sense or at least are incomplete, as it does not mention what to initialise. Types cannot be initialised per definition. Only "instantiated" types can be intialised. So either this assingment is unfullfilable, or one needs to assume an implicit instantiation of the type defined.
However, doing the latter, in C one needs two steps to achieve this.
Define the type:
typedef int[10] Marks;
Define the variable using the type defined in 1. and initialise it:
Marks marks = {0};
Give a type definition suitable for representing the assignment
marks for 10 students and initialised (??) all marks to zero.
The word "initialized" doesn't make sense. I assume they ask you to "initialize" instead.
Give a type definition suitable for representing the assignment
marks for 10 students and initialise all marks to zero.
So they ask you to do two things, "give a type definition" and "initialize all marks", preferably in one line of code (?).
What is a type definition? Is it something that has typedef in it? I guess not! I understand it as "something that defines a type". For example:
struct Marks {int marks[10];};
Yeah, this thing defines a type with the ugly name struct Marks. Since this doesn't have typedef in it, you actually can define a variable of that type, and initialize that variable, all in the same line of code:
struct Marks {int marks[10];} stuff = {{0}};
Answer for C++:
There are very few places in C++ where datatype definitions contain any "value" data. I can only think of a few:
Enums
Template parameters
Function parameters that have default values
Otherwise, data and the data type are always separated. You can't specify the initial value of a type in the definition.
Something is confusing about your question: you say
typedef int foobar[10]; //is accepted but is not initialised
Understand that this is only a datatype definition; there is nothing yet to initialize.
foobar x = {0};// this should compile and work fine.
But the initialization is done when you instantiate the type, not in the type definition.
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
};
};
Just started with K & R and on the 2nd chapter, there is the line:
Declarations list the variables to be
used and state what type they have and
perhaps what their initial values are.
So:
int x = 42 is a definition.
and int x is a declaration but also a definition since every definition is a declaration.
But when we assign an intial value like K & R say, doesn't that make the declaration a definition?
You confuse two things:
A declaration states (declares) what an object's* type, name and scope is
A definition defines what a object's content is
* object as in: variable, function etc., not an OOP object.
A definition is hence very often also a declaration, since you cannot define what is in an object when you do not state what the type of the object is. Easiest to remember is just: "Every definition is a declaration, but not every declaration is a definition"
For variables
There is only 1 way to declare without defining the variable:
extern typeX variable_name
This tells the compiler that there is a variable called variable_name with type typeX, but not where to get it.
Every other way to declare a variable is also a definition, since it tells the compiler to reserve space for it and perhaps give it an initial value.
The difference is much clearer in structs and functions:
For Structs
A declaration:
struct some_struct{
int a;
int b;
}
This declares some_struct to the compiler with a and b as struct variables both with type int.
Only when you define them space is reserved and you can use them:
void foo(){
struct some_struct s;
s.a = 1; // For this to work s needs to be defined
}
For functions:
The difference is much more clear
declaration:
// This tells the compiler that there is a function called "foo" that returns void and takes void arguments
void foo();
A definition could be like the one above (in the struct part)
Basically you can say that a declaration simply tells the compiler that there is somewhere a variable with that name and type. It does produce any code, and in C, this has to be done with the extern keyword on variables. Function prototypes (without implementation) are also mere declarations, and don't need the extern keyword, but you can still provide it.
A definition produces code, e.g. allocates memory on the stack or heap for a variable, or the body for methods.
In that sense, both of your statments are definitions, and any definition is also a delcaration.
I think that might by a mistake by K&R...