Click here to Skip to main content
15,747,637 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.
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 -[^]

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

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:
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 -[^]

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:
The only illegal modification is this:
because the item pointed to by score is <code>const, but score itself is not.
Share this answer
CPallini 5-Dec-22 2:19am    

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