Home > Backend Development > C++ > body text

How to Correctly Declare Multiple Pointers in a Single Line in C ?

Linda Hamilton
Release: 2024-10-27 03:28:02
Original
260 people have browsed it

How to Correctly Declare Multiple Pointers in a Single Line in C  ?

Declaring Multiple Pointers in a Single Line: Understanding the Syntax

When declaring multiple object pointers on a single line in C , a common pitfall can arise if the syntax is not correctly understood. Consider the following code:

<code class="cpp">private:
    sf::Sprite* re_sprite_hair;
    sf::Sprite* re_sprite_body;
    sf::Sprite* re_sprite_eyes;</code>
Copy after login

This code successfully declares three pointers pointing to objects of type sf::Sprite. However, changing the syntax to the following format results in a compiler error:

<code class="cpp">private:
    sf::Sprite* re_sprite_hair, re_sprite_body, re_sprite_eyes;</code>
Copy after login

The Reason:

The difference between these two declarations lies in the presence of the asterisk * in the second version. In C , the asterisk denotes the declaration of a pointer. When omitted, it results in the declaration of the object itself.

In the first version, each variable has an asterisk, indicating that all three are pointers. In the second version, the asterisk is only applied to re_sprite_hair, making it a pointer, while re_sprite_body and re_sprite_eyes become objects of type sf::Sprite. This incorrect syntax results in the compiler error seen.

The Correct Syntax:

To correctly declare multiple pointers on a single line, it is crucial to use the asterisk for each variable. The correct syntax would be:

<code class="cpp">private:
    sf::Sprite* re_sprite_hair, *re_sprite_body, *re_sprite_eyes;</code>
Copy after login

By applying the asterisk to each variable, the compiler recognizes all three as pointers, and the declaration is valid.

The above is the detailed content of How to Correctly Declare Multiple Pointers in a Single Line 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!