Home > Backend Development > C++ > How Can I Write a Short Literal in C ?

How Can I Write a Short Literal in C ?

Patricia Arquette
Release: 2024-10-31 11:18:02
Original
867 people have browsed it

How Can I Write a Short Literal in C  ?

Writing Short Literals in C

In C , there are predefined literals for various data types, such as int, long, and double. However, there is no dedicated literal for short. To write a short literal, you can use a cast, as demonstrated below:

<code class="cpp">((short)2)  // This assigns the short literal value 2 to a variable of type short</code>
Copy after login

While not an explicit short literal, this approach behaves similarly and effectively assigns a short value to a variable.

Despite the absence of a direct short literal notation, the compiler typically optimizes the code such that it treats the casted integer as a short, without incurring significant performance overhead. For example, the following code:

<code class="cpp">short a = 2L;
float b = 2.0;
short c = (short)2;
char d = '';</code>
Copy after login

When compiled and disassembled, results in the following machine code:

movl    , _a
movl    , _b
movl    , _c
movl    , _d
Copy after login

This indicates that the compiler directly assigned the value 2 to all four variables, regardless of their data types. Therefore, you do not need to be overly concerned about performance implications when using this casting approach to write short literals.

The above is the detailed content of How Can I Write a Short Literal 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template