Home > Article > Backend Development > How Do You Write Short Literals in C ?
Writing Short Literals in C
In C , several literal notations are used to represent different data types, such as 2 for int, 2L for long, and '2' for char. However, it may be unclear how to write literals for short, which stores 16-bit integers.
The problem becomes apparent when trying to use 2S as a short literal. While this notation may seem logical, it results in a compiler warning. The solution lies in using a cast to explicitly convert an integer to a short.
To write a short literal in C , follow these steps:
This approach is not strictly a short literal, but it behaves similarly. C does not offer a direct way to represent short literals.
Despite this, the compiler optimizes the code such that it allocates memory for a short rather than an int. Here's an example that demonstrates this behavior:
<code class="cpp">int a = 2L; double b = 2.0; short c = (short)2; char d = '';</code>
When compiled and disassembled, the generated assembly code reveals that all variables are allocated memory as if they were the correct types:
movl , _a movl , _b movl , _c movl , _d
Therefore, you need not concern yourself with the inefficiency of casting when working with short literals in C .
The above is the detailed content of How Do You Write Short Literals in C ?. For more information, please follow other related articles on the PHP Chinese website!