[PATCH v3 02/25] util: virtypedparam: Use proper enum type for all switch() statements

Martin Kletzander mkletzan at redhat.com
Wed Apr 19 13:14:01 UTC 2023


On Wed, Apr 19, 2023 at 03:08:03PM +0200, Peter Krempa wrote:
>On Wed, Apr 19, 2023 at 15:02:34 +0200, Martin Kletzander wrote:
>> On Wed, Apr 19, 2023 at 02:04:19PM +0200, Peter Krempa wrote:
>> > Ensure that all switch statements in this module use the proper type in
>> > switch() statements to ensure complier protections.
>> >
>> > Signed-off-by: Peter Krempa <pkrempa at redhat.com>
>> > ---
>> > src/util/virtypedparam.c | 12 ++++++++----
>> > 1 file changed, 8 insertions(+), 4 deletions(-)
>> >
>> > diff --git a/src/util/virtypedparam.c b/src/util/virtypedparam.c
>> > index 0cca16053d..974ec51a79 100644
>> > --- a/src/util/virtypedparam.c
>> > +++ b/src/util/virtypedparam.c
>> > @@ -170,7 +170,7 @@ virTypedParameterToString(virTypedParameterPtr param)
>> > {
>> >     char *value = NULL;
>> >
>> > -    switch (param->type) {
>> > +    switch ((virTypedParameterType) param->type) {
>> >     case VIR_TYPED_PARAM_INT:
>> >         value = g_strdup_printf("%d", param->value.i);
>> >         break;
>> > @@ -192,6 +192,7 @@ virTypedParameterToString(virTypedParameterPtr param)
>> >     case VIR_TYPED_PARAM_STRING:
>> >         value = g_strdup(param->value.s);
>> >         break;
>> > +    case VIR_TYPED_PARAM_LAST:
>> >     default:
>>
>> To ensure compiler protection in switch() statements you should also
>> remove the default case from the switch statements.
>
>It actually works properly even with the 'default' case being present.
>Additionally in case a caller passes in something which is not actually
>a proper enum value (e.g. by typecasting) the 'default' case will be
>applied.
>

Oh, good to know, TIL then.  In the meantime I replied as well =)

>In many new places we already do it like this.
>
>>
>> With that changed:
>>
>> Reviewed-by: Martin Kletzander <mkletzan at redhat.com>
>
>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://listman.redhat.com/archives/libvir-list/attachments/20230419/3a5339cd/attachment.sig>


More information about the libvir-list mailing list