Click here to Skip to main content
15,878,945 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Below is a code snippet of C++ which seems not legal in my understanding of C++:

Are the three statements (from #1 till #3) initialization of three constant variables, high, low, and score? If yes, where can I find a tutorial for such initialization? I didn't have such kind of coding before.

int main()
{
 
    int high{ 100 };  // #1
    int low{ 66 };    // #2
    const int* score{ &high };  // #3
// .....
}


What I have tried:

I googled some terms about 'constant initialization in c++' but can't figure it out.
Posted
Updated 4-Dec-22 20:34pm

C++ 11 introduced "Uniform initialization", so you can use curly brace pairs to initialize basic types, classes, structs, unions.

int high{ 100 };  // #1
int low{ 66 };    // #2
const int* score{ &high };  // #3


high\low are not const variables, but two variables which were assigned as const values.
score is a const pointer variable, so you cannot change the value of *score.

please reference:

Initialization - cppreference.com[^]

https://learn.microsoft.com/en-us/cpp/cpp/initializers?view=msvc-170

Brace initialization for classes, structs, and unions | Microsoft Learn[^]
 
Share this answer
 
All you initialization involve variables (insted of constants). Namely
Quote:
int high{ 100 }; // #1
int low{ 66 }; // #2
Intialize two variables with constant (literal) values.

Quote:
const int* score{ &high }; // #3
Initialize a variable (pointer) with the address of another variable. You cannot change the original variable value via the pointer, because of the const in the declaration.

If you really want constants (instead of variables) then you have to write something similar to:
C++
const int High{ 100 };
const int Low{ 66 };
const int * const PtrScore { &High };
I suggest you to try cdecl: C gibberish ↔ English[^].
 
Share this answer
 
See here: Initialization - cppreference.com[^]

But none of those are const variables, with the "sort of" exception of that last as they can all be modified - these are legal and working:
C++
high++;
low++;
score++;
The only illegal modification is this:
C++
(*score)++;
because the item pointed to by score is <code>const, but score itself is not.
 
Share this answer
 
Comments
CPallini 5-Dec-22 2:19am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900