Better enums in C (Arduino) - c

I thought the below was a neat way to implement enums in C.
struct states
{
enum
{
waitPackage,
waitReference,
waitData
};
}state;
This adds some type safety and I can also acces each member through state.XXX which I think is a lot more neat than prepend all the names of the enum items, and access the members in a fashion like state_XXX. Or what do you think, have I missed something?
However, I cant use the enum above in a switch-case statement as the compiler says that state isn't a constant.
Is there a way to tell the compiler that I don't intend to change the members of the enum ot it could be used in switch-case? Or another way to accomplish what I would like here?
In a C++ I solved it by placing the enums in namespaces but thats a not an option here.

Types in C are always global and never nested. So there is no way to have scoped constants.
Thus the :: notation is not allowed in C, it is not part of the syntax. E.g your constants as waitPackage are visible as such everywhere.

Related

How to have two structs with same type and name in different header files without conflicts?

I already have, say, a struct smallbox with two primitive variables (int identifier, int size) in it. This smallbox is part of higher structs that are used to build i.e. queues.
Now, I have in a part of my project an issue for which I came up with the solution to expand this smallbox, so it has another piece of information like int costs_to_send_it. While, I am not allowed to change my basis structs, is there a way to expand this struct in some fashion like methods overloading in java or so? Will I still be able to use all operation that I have on my higher structs while having the new struct smallbox with the new attribute inside instead of the old one?
This sentence determines the answer: “[Will] I still be able to use all operation that I have on my higher structs while having the new struct smallbox with color attribute inside instead of the old one?” The answer is no.
If the headers and routines involved were completely separate, there are some compiling and linking “games” you could play—compiling one set of source files with one definition of the structure and another set of source files with another definition of the structure and ensuring they never interacted in ways depending on the structure definition. However, since you ask whether the operations defined using one definition could be used with the alternate definition, you are compelling one set of code to use both definitions. (An alternate solution would be to engineer one source file to use different names for its routines under different circumstances, and then you could compile it twice, once for one definition of the structure and once for another, and then you could use the “same” operations on the different structures, but they would actually be different routines with different names performing the “same” operation in some sense.)
While you could define the structure differently within different translation units, when the structure or any type derived from it (such as a pointer to the structure) is used with a routine in a different translation unit, the type the routine is expecting to receive as a parameter must be compatible with the type that is passed to it as an argument, aside from some rules about signed types, adding qualifiers, and so on that do not help here.
For two structures to be compatible, there must be a one-to-one correspondence between their members, which must themselves be of compatible types (C 2018 6.2.7 1). Two structures with different numbers of members do not have a one-to-one correspondence.
is there a way to expand this struct in some fashion like methods
overloading in java or so?
In method overloading, the compiler chooses among same-named methods by examining the arguments to each invocation of a method of that name. Observe that that is an entirely localized decision: disregarding questions of optimization, the compiler's choice here affects only code generation for a single statement.
Where I still be able to use all operation
that I have on my higher structs while having the new struct smallbox
with color attribute inside instead of the old one?
I think what you're looking for is polymorphism, not overloading. Note well that in Java (and C++ and other the other languages I know of that support this) it is based on a type / subtype relationship between differently-named types. I don't know of any language that lets you redefine type names and use the two distinct types as if they were the same in any sense. Certainly C does not.
There are some alternatives, however. Most cleanly-conforming would involve creating a new, differently-named structure type that contains an instance of the old:
struct sb {
int id;
int size;
};
struct sb_metered {
struct sb box;
int cost;
}
Functions that deal in individual instances of these objects by pointer, not by value, can be satisfied easily:
int get_size(struct sb *box) {
return sb->size;
}
int get_cost(struct sb_metered *metered_box) {
return metered_box->cost;
}
int main() {
struct sb_metered b = { { 1, 17}, 42 };
printf("id: %d, size: %d, cost: %d\n",
b.id,
get_size(&b.box),
get_cost(&b));
}
Note that this does not allow you to form arrays of the supertype (struct sb) that actually contain instances of the subtype, nor to pass or return structure objects of the subtype by value as if they were objects of the supertype.

How to exclude an C enum case when using the type in Swift

In my C code I generally have an enum case called count at the end. But when I use my enum in Swift it will also have that value, which I must handle in switch statements.
Is there some attribute I can use to exclude a case when importing into Swift?
You can use the NS_SWIFT_UNAVAILABLE macro on enumerators:
typedef NS_ENUM(unsigned, Foo) {
bar,
baz,
count NS_SWIFT_UNAVAILABLE("Count does not represent a case")
};
NS_SWIFT_UNAVAILABLE, like any __attribute__ that you want to apply to an enumerator, goes after the enumerator name but before the = if you need one.
The macro is defined if you include <Foundation/Foundation.h>. If you include CoreFoundation, you get CF_SWIFT_UNAVAILABLE, which does the same thing. If you include neither, you can use the long form:
__attribute__((availability(swift, unavailable, message="your message")))
Enumerators that are annotated with NS_SWIFT_UNAVAILABLE won't show up in autocomplete, and won't cause build issues if they're not handled on the Swift side. If you attempt to use it, you get a hard error that includes your message.
Keep in mind that starting with Swift 5, you may need to use NS_CLOSED_ENUM instead of NS_ENUM if your purpose is to avoid having a default case.

C modify const members in a struct

I am designing an API and the key part of it is a struct returned by the API with lots of const members. Also, there are both const pointers and pointers to const variables. Inside the implementation I need to modify this struct. Currently, I have defined exactly the same struct but with dropped const keywords and a different name. Inside the API calls I just cast external struct to the internal one.
Is there any way to code in a better way? The current design is prone to errors if I modify one struct and forget about the other.
Use opaque structs and accessor functions
The opaque structs provide a name for your API, but no way to address the fields.
The accessor functions in your API provide whatever controlled access you like.
Just a note here: These field aren't really non writable.
You want to make them kinda "private" but every programmer can access them this way:
typedef struct
{
const int x;
}mystruct;
Then:
mystruct ms= {0};
*((int*)&(ms.x)) =4;
printf("%d",ms.x);
Because the const specifier just prevents programmers from modifying them at compile time.But at runtime the memory isn't readonly.
I still think that the const specifier is useful: if a good programmer sees it, says then I shouldn't access that field.If instead wants to make the smart guy access the fields and potentially risk an inconsistent state.
So if you are sure that these const field can be changed, at your place I would use this way.I know that pedantic programmer will not like it, I don't like it too but sometimes we gotta bypass this.
Duplication is the root of all evil, so instead of duplicating the structure definition you could do something like this:
#ifndef CONST
#define CONST const
#endif
struct mystruct
{
CONST void * my_data;
};
Now you just define CONST to be empty before including the header file in the private implementation.
However, like the other answers suggest, this is not a very good idea. First there's probably better and cleaner ways of acheiving what you want. Second this could lead to strange and unwanted results as the compiler may use the constness of the fields to optimize the code.
In short, I think you would be better off rethinking your API.

How to name variables which are structs

i often work on private projects using the WinApi, and as you might know, it has thousands of named and typedefed structs like MEMORY_BASIC_INFORMATION.
I will stick to this one in my question, what still is preferred, or better when you want to name a variable of this type. Is there some kind of style guide for this case?
For example if i need that variable for the VirtualQueryEx function.
Some ideas:
MEMORY_BASIC_INFORMATION memoryBasicInformation;
MEMORY_BASIC_INFORMATION memory_basic_information;
Just use the name of the struct non capitalized and with or without the underlines.
MEMORY_BASIC_INFORMATION basicInformation;
MEMORY_BASIC_INFORMATION information;
Short form?
MEMORY_BASIC_INFORMATION mbi;
I often see this style, using the abbreviation of the struct name.
MEMORY_BASIC_INFORMATION buffer;
VirtualQueryEx defines the third parameter lpBuffer (where you pass the pointer to the struct), so using this name might be an idea, too.
Cheers
In general, it's discouraged to name variables based on their type. Instead, try to provide additional information about the specific context and purpose of the usage.
Using the MEMORY_BASIC_INFORMATION example, consider what the context is of the structure. Are you using the information to iterate over a number of such information structures? Then maybe
MEMORY_BASIC_INFORMATION currentFrame;
Or if you're performing a test on the memory info for some status, maybe it's a candidate.
MEMORY_BASIC_INFORMATION candidate;
Now you can write documentation like "test candidate structure for ...".
You may find that you still want to include type information using the type prefix location. If this is the case, you might call it mbiCurrentFrame or mbiCandidate.
If the purpose or context is truly abstract, such as is the case with the API functions themselves, I would chose something simple and direct, such as info or buffer, except in the case where those names could somehow be misinterpreted in the context.
I think it depends upon a number of issues, and you just have to find the best balance when striving for readability.
Window width
Variables/types of similar names used in the routine.
That being said, if I can get away with it, I would probably use ...
MEMORY_BASIC_INFORMATION info;
If there were other similar types or variable names, then I would add some sort of descriptive modifier such as ...
MEMORY_BASIC_INFORMATION memBasicInfo;
Or, if window real-estate was limited (some projects I have worked on have insisted upon 80 char line maximum), I could go for ...
MEMORY_BASIC_INFORMATION mbi;
But to make it as readable as possible, I try to be consistent--and that I think is one of the most important things to keep in mind.
A little all over the place, but I hope it helps.
Try and keep the case and acronym of the typedef, e.g.
MEMORY_BASIC_INFORMATION MBI_temp
I deal with a lot of code that is and must remain portable across Linux and Windows, this was also a problem for us.
You could also do it in camel case:
MEMORY_BASIC_INFORMATION MBITemp
.. but that doesn't seem as self explanatory.
The point is, anyone familiar with those structures should recognize them as what they are rather quickly. Just be sure not to tromp on another namespace.
The key is, just be consistent in each tree that you work on. Its really only a noticeable issue in two cases:
Globals
Mile long functions
If you have functions so long that you have to scroll up five pages to the declarations just to see what a variable is, there's larger problems to deal with than variable nomenclature :)
Annoyingly, this might introduce some weirdness due to syntax highlighting picking it up as a constant, but that's also the case for the underlying typedef.

How do I create an array of namespaces?

How can I create an array of namespaces? And because it seems like a long shot, if this is impossible, is there something similar to a namespace that can be made into an array?
The namespace, if it helps, contains these variables:
const int maxx=// depends on the particular namespace
// I need an array to go through each namespace and
// pick out the variable
const int maxy=// depends on particular namespace
//prgm is a class I made
prgm sector[maxx][maxy];
// another array of prgms. int is my shorthand of saying "depends on
// particular namespace", so is char.
prgm programs[int]={prgm1(int,int,char),prgm2(int,int,char)...
So any help would be welcome.
You could use reflection, but I think you should rethink your design.
I am not sure what language you are talking about, but in many (most?) languages, references to constants are replaced by the constant value at compile time. So they are no longer present at runtime and even reflection won't help.
You could create a class in each namespace that exposes the constants as (static) properties. Then you can use reflection to search the class in each namespace and obtain the constant values from the properties.
But, as mentioned by others, you should really rethink your design. Finally, namespaces are usually not accessable via reflection because they just extend the class names of the contained classes (and other stuff). Or is there a (non-esoteric) language that exposes namespaces as entities via reflection?
For .NET the reference for the System.Type.Namespace property states the following.
A namespace is a logical design-time naming convenience, used mainly to define scope in an application and organize classes and other types in a single hierarchical structure. From the viewpoint of the runtime, there are no namespaces.
Is this supposed to be C++? Sounds like you need to define a class, not a namespace, then create instances (objects) of that class and put them in an array.
So the sector variable gets tricky, since it is sized based on the value of maxx and maxy parameters that would be passed to the constructor of the class. You can take care of that problem by using a container class or a dynamically-allocated multi-dimensional array instead.
If you talk about C++, in there you can't pass namespaces as entities around. But you can do so with types, as type argument to templates. In this case, an MPL sequence could help together with MPL algorithms:
struct c1 { typedef int_<2> value_x; };
struct c2 { typedef int_<3> value_x; };
struct c3 { typedef int_<1> value_x; };
template<typename C> struct get_x : C::value_x { };
typedef vector<c1, c2, c3> scope_vec;
typedef max_element<
transform_view< scope_vec , get_x<_1> >
>::type iter;
You may then create your array like
prgm programs[deref< iter >::type::value];
Note that the search within that type-vector happens at compile time. So the value of the array is determined at compile time either.

Resources