Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use enumerations in C language

Shulou Source: shulou.com Published: 2022-05-31 18:33:54 09月21日 Update

This article mainly introduces "how to use the enumeration of C language". In the daily operation, I believe that many people have doubts about how to use the enumeration of C language. The editor consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubt of "how to use the enumeration of C language"! Next, please follow the editor to study!

Overview

A type whose value can only be one of a bunch of values.

For example, what day of the week, it will only be Monday to Sunday.

In numerical terms, it is 0 to 6, but 0 to 6 is not easy to understand.

Enumerations can be expressed in words, which improves readability.

In essence, it's still 0 to 6.

Getting started with simple use

Create three new variables with values of a b c

# includeenum Gender {Male, Female, Empty}; int main () {enum Gender a = Male; enum Gender b = Female; enum Gender c = Empty; printf ("% d\ n", a); printf ("% d\ n", b); printf ("% d\ n", c); return 0;}

Effect: 0 1 2

Judge

As a numerical value, you can certainly participate in the judgment.

# includeenum Gender {Male, Female, Empty}; int main () {enum Gender a = Male; printf ("% d\ n", a = = Male); return 0;}

Effect: 1, true.

Custom numeric value

The default is 01234...

Can be customized.

# includeenum Gender {Male = 2, Female = 4, Empty = 6}; int main () {enum Gender a = Male; printf ("% d\ n", a); return 0;}

Effect: 2

A lax way of writing

In C language, you can assign values directly.

There is nothing wrong with the following code:

# includeenum Gender {Male, Female, Empty}; int main () {enum Gender a = 0; printf ("% d\ n", a = = Male); return 0;}

Effect:

But it is not recommended.

At this point, the study of "how to use the enumeration of C language" is over. I hope to be able to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Language effects numerical values learning week more questions help practicality next three code writing words variables readability that is suggestions articles methods Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Docker Linux vpn Shulou Technology