Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is this syntax of wrapping an enum type in parentheses?

There’s this really weird syntax that I don’t understand. On the libcurl site documentation there’s an enum defined as:

typedef enum {
  CURLSSLBACKEND_NONE = 0,
  CURLSSLBACKEND_OPENSSL = 1, /* or one of its forks */
  CURLSSLBACKEND_GNUTLS = 2,
  CURLSSLBACKEND_NSS = 3,
  CURLSSLBACKEND_GSKIT = 5, /* deprecated */
  CURLSSLBACKEND_POLARSSL = 6, /* deprecated */
  CURLSSLBACKEND_WOLFSSL = 7,
  CURLSSLBACKEND_SCHANNEL = 8,
  CURLSSLBACKEND_SECURETRANSPORT = 9,
  CURLSSLBACKEND_AXTLS = 10, /* deprecated */
  CURLSSLBACKEND_MBEDTLS = 11,
  CURLSSLBACKEND_MESALINK = 12, /* deprecated */
  CURLSSLBACKEND_BEARSSL = 13,
  CURLSSLBACKEND_RUSTLS = 14
} curl_sslbackend;

Then it calls a function called "curl_global_sslset() with the enum type wrapped in parentheses minus 1:

 /* list the available ones */
  const curl_ssl_backend **list;
  curl_global_sslset((curl_sslbackend)-1, NULL, &list);

This is really weird syntax to me, and I was surprised to find that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int r = (curl_sslbackend) - 1; 

Equals -1. But why? curl_sslbackend is a type, how can you use a minus operator on a type? What is happening here?

>Solution :

When you put a type name in parentheses, it’s a type cast. It means to convert the value after it to the specified type.

-1 is not subtraction, it’s a negative integer.

So

int r = (curl_sslbackend) -1; 

means to convert the integer -1 to the curl_sslbackend enum type, then assign this value to the integer r. So you’re converting an integer to an enum, then converting the enum back to an integer. Which is basically a no-op, so it’s the same as

int r = -1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading