Home > Backend Development > C++ > body text

\'const int\' vs. \'int const\' in C and C: Are They Really the Same?

DDD
Release: 2024-10-27 02:06:30
Original
688 people have browsed it

'const int' vs. 'int const' as Function Parameters in C and C

When declaring function parameters with const, it's crucial to distinguish between 'const int' and 'int const'. While they may seem identical, the order of the modifiers changes the interpretation of the declaration.

'const int' declares a variable that is constant (cannot be modified) and of type int. The emphasis here is on the const qualifier being applied to the variable.

'int const', on the other hand, declares a variable that is of type int and also constant. In this case, the const qualifier modifies the type, not the variable.

So, are these two functions identical?

<code class="c">int testfunc1 (const int a) { return a; }
int testfunc2 (int const a) { return a; }</code>
Copy after login

Yes, they are equivalent. Reading the declaration backwards clarifies this.

For 'const int':

  • "a" is an integer that is "constant".

For 'int const':

  • "a" is a "constant integer".

In both cases, "a" is both an integer and a constant.

However, the backward-reading trick becomes invaluable in complex declarations:

<code class="c">// "s" is a pointer to a char that is constant
const char *s;

// "t" is a constant pointer to a char
char *const t = &c;

// The char in "s" is constant, so you can't modify it
*s = 'A'; // Can't do

// The pointer in "s" is not constant, so you can modify it
s++; // Can do

// The char in "t" is not constant, so you can modify it
*t = 'A'; // Can do

// The pointer in "t" is constant, so you can't modify it
t++; // Can't do</code>
Copy after login

Remember, in C , const data members can be initialized either in the class declaration or in the constructor. Whereas in C, const data members are considered as symbolic constants and must be initialized in the declaration, which makes them very close to #define.

The above is the detailed content of \'const int\' vs. \'int const\' in C and C: Are They Really the Same?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!