Saturday, April 19, 2025

C++ Variables

Think about variables as names for containers where we will store data. Once we create variable there's no need to change their names, just values if we need to do that. We will use variables all the time, not just in C++ but also in many other programming languages.

In this example, we are creating variable "number" with value 10. Variable is whole number and in C++ we must state what is data type for variable so int (integer) is used.

Variable is created inside main() function, and after that it's printed using cout on dedicated line. Once we have variable created we can use it meny times. Run this code:

#include <iostream>

using namespace std;

int main() {

    int number = 10;

    cout << number << endl;

    return 0;

}

Result:

10

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

We can create and use more than one variable with dedicated values, on dedicated lines. Multiple times if we need to:

#include <iostream>

using namespace std;

int main() {

    int number = 10;
    int container = 5000;
    int port_number = 80;

    cout << number << endl;
    cout << container << endl;
    cout << "------------------------" << endl;
    cout << port_number << endl;
    cout << "------------------------" << endl;

    return 0;

}

Result:

10
5000
------------------------
80
------------------------

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

We can align endlines vertically, but result will be the same: 

#include <iostream>

using namespace std;

int main() {

    int number = 10;
    int container = 5000;
    int port_number = 80;

    cout << number                      << endl;
    cout << container                   << endl;
    cout << "------------------------"  << endl;
    cout << port_number                 << endl;
    cout << "------------------------"  << endl;

    cout << container                   << endl;
    cout << container                   << endl;

    return 0;

}

Result:

10
5000
------------------------
80
------------------------
5000
5000

Process returned 0 (0x0)   execution time : 0.050 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 .  ...