Saturday, April 19, 2025

C++ Constants - const

Constants represent fixed values if we know in advance that there's no need to change them during program execution.

As with variables, they can be of any data type. They are extremely useful when we know what type of "inputs" are fixed in time.

They must be defined above main() section of our program.

One way to do that is to use keyword "const" on far left side than data type than name for a constant and finally, their value.

As with any instruction in C++, semicolon must be used at the end of lines dedicated for constants: 

#include <iostream>

using namespace std;

const float pi = 3.14;
const char let = 'Z';
const int vol_lev = 5;
const string head_line = "-------------------------";

int main() {

    cout << head_line << endl;
    
    cout << "PI Value: " << pi << endl;
    cout << "Letter: "   << let << endl;
    cout << "Voltage: "  << vol_lev << endl;
    
    cout << head_line << endl;

    return 0;

}

Result:

-------------------------
PI Value: 3.14
Letter: Z
Voltage: 5
-------------------------

Process returned 0 (0x0)   execution time : 0.114 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...