Home > Backend Development > C++ > How Do You Write Short Literals in C ?

How Do You Write Short Literals in C ?

DDD
Release: 2024-10-31 00:29:03
Original
701 people have browsed it

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:

  1. Cast an integer to short: Enclose an integer literal within parentheses and cast it to short. For example: (short)2

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>
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template