#C enums help, rust enums, rewriting cbonsai in rust

17 messages · Page 1 of 1 (latest)

native edge
#

I'm currently in the process of rewriting John Allbritten's cbonsai in rust and im having some trouble with C's enums.

Here's my issue.

In line 698 in https://gitlab.com/jallbrit/cbonsai/-/blob/master/cbonsai.c

A custom branch function is called (function below).

branch(conf, objects, myCounters, maxY - 1, (maxX / 2), trunk, conf->lifeStart);

If you look at the function in line 416 these parameters are passed in.

void branch(struct config *conf, struct ncursesObjects *objects, struct counters *myCounters, int y, int x, enum branchType type, int life)

You can see the branchType enum that is passed in line 698 named 'trunk' (enum in line 17).

Now my confusion is with enums themselves, I have a poor understanding of them, especially what determines the values, such as the ones of 'trunk' in line 698, so how does cbonsai choose what type branchType actually is?

note this is my first time working with c but understand many of the concepts as it is very similar to the same capabilities rust has.

#

Any help would be appreciated

verbal folio
#

An enum is a value itself. Much like 1 is a value the branchType trunk is a value. You're just defining your own named values. Makes code easier to understand because rather than magical numbers with secret meanings, you can use an enum and set a value with a name. They're handier than just having a bunch of variables that you assign to a number because an enum will ensure the value set is only a valid value.

For example

int TRUNK = 0;
int SHOOT_LEFT = 1;
...
int type = TRUNK;  // Valid type
...
int type = 10;  // Invalid type, allowed because it's a valid int


// Using an enum
enum brachType = {trunk, shootLeft...}
enum brachType type = trunk; // Valid type
...
enum brachType type = foobar; // Invalid type, compiler raises an error
#

So enums are just a way for you to create your own values and constrain them so that invalid values cannot be assigned.

native edge
#

ohhhhh

#

okay

#

Thank you Zech!

verbal folio
#

Np

native edge
native edge
# verbal folio Np

I dont think i see where branchtype is being changed in cbonsai, is there something im missing

verbal folio
#

Being changed???

native edge
# verbal folio Being changed???

I think I have worded this poorly, I’m not sure where cbonsai defines an enum type such as in the example you provided on top and give it a value let’s say of “trunk” to then use it later. Is there something I’m missing about enums?

verbal folio
#

Line 17 of the file you linked defines the enum???

#

Sorry my code was incorrect because I put an =

#

I don't write C very often

native edge