Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing integer to a function that has enum as input parameter

Tags:

c

enums

capl

I've got a question

What shall happen if we have the following :

typedef enum  {s1=0,s2,s3} states ;

void test( states x ) ;

when using the function test , what happens if I use it like the following :

test(6);

Shall it be mapped to the nearest enum value , or it needs to be handled in the function implementation ?

like image 358
Mohammed Abdelhamid Avatar asked Jun 13 '26 17:06

Mohammed Abdelhamid


2 Answers

enum are effectively treated as int by most C compilers. They are just syntactic sugar to make code more readable. In your case, 6 will be passed to the function and the function has to handle it.

like image 59
Akhi Avatar answered Jun 15 '26 16:06

Akhi


[for C]

If doing

test(6);

6 will be passed to test() (as enums are (treated as) ints) and it shall be trapped by the function's input validation.


Update:

Input validation is not done automagically. It needs to be coded explicitly.

like image 27
alk Avatar answered Jun 15 '26 15:06

alk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!