2

After many years of reading on this site (and getting many helpful solutions), it's time for me to ask a question:)

I was wondering about the default enum values. I'm using enums to send error codes from an MCU to a PC (and vice versa)

is it a good practice (and safe) to define enums like this

C:

typedef enum
{
no_error = 0,
error_1
error_2,
...
}

C#

enum
{
no_error = 0,
error_1,
error_2,
}

All enum values are cast into Uint32 before Transfer. Can I always assume that error_1 = 1 and error_2=2 on C and C# side?

I'm using the GCC Compiler.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
JuliusCaesar
  • 341
  • 3
  • 14
  • This [link](https://stackoverflow.com/questions/6434105/are-default-enum-values-in-c-the-same-for-all-compilers) have the answer. – Viki Theolorado Sep 29 '17 at 08:35
  • 2
    Yes, the C# enum type was intentionally crippled to work well in interop. Technically you need to pay attention to the base type for the enum, in practice it is a 32-bit `int` for both C# and C. – Hans Passant Sep 29 '17 at 08:36
  • `= 0` is *optional* too in C# ([*the first enumerator has the value 0*](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/enum)), though it's [against guidelines](https://stackoverflow.com/a/7257458/1997232). – Sinatr Sep 29 '17 at 09:00

2 Answers2

3

Yes, both languages guarantee that if you don't explicitly give an enum value as integer value then it is one more than the previous enum value.

Sean
  • 60,939
  • 11
  • 97
  • 136
0

Yes in C# if you start an enum with 0 then consecutive enum should be consecutive numbers. In your example as no_error = 0 then error_1 would be 1. Also in C it is the same. Say for example in C,

enum DAY           
{

sunday = 0,    
monday,     
tuesday,  
wednesday,      ****/* wednesday is associated with 3 as Sunday is 0*/****  
thursday,  
friday  

} workday;  
Vijayanath Viswanathan
  • 8,027
  • 3
  • 25
  • 43