Showing posts with label Variable. Show all posts
Showing posts with label Variable. Show all posts

Local, Global, Global Constant, and Static Variable

In this tutorial from our C++ e-book, we will learn a little more about the relationship between functions and variables, knowing the local, global, constant, and static variables types.

Local variable

When we declare a variable within a function, we say that it is local.
This is due to the fact that it 'exists' only for those who are within the function, that is, only inside can see it and its value.

Other commands in other functions cannot access it normally.
To illustrate this, let's declare the variable myVar with value 1, inside main().

Next, let's call the print () function, which will print the value of myVar:
#include <iostream>
using namespace std;

void print()
{
    cout<<myVar;
}

int main()
{
    int myVar=1;
    print();
    return 0;
}
This code is neither compiled, the error appears:
"'myVar’ was not declared in this scope | "

That is, the myVar variable is not within the scope of the print() function, it is as if it did not exist.

The opposite also applies:
#include <iostream>
using namespace std;

void print()
{
    int myVar=1;
}

int main()
{
    cout<<myVar;
    return 0;
}
That is, not even the main() function can see the internal content of the print() function.

Now let's declare myVar both inside print() and inside main(), and let's print both values:
#include <iostream>
using namespace std;

void print()
{
    int myVar=1;
    cout << "In print() = "<<myVar<<endl;
}

int main()
{
    int myVar=2;
    cout << "In main() = "<<myVar<<endl;
    imprime();
    return 0;
}
Results
C++ Progressive e-book

That is, we can declare variables of the same name, but in different functions.
And the functions only 'see' what's inside that function, ok?

Global variable

There is a way to make the same variable seen and accessed by several functions, just make it a global variable.

To do so, simply declare it outside the scope of functions.
For example, let's declare the variable pi, and store the value of pi.

Next, we will ask the radius value from the user, and using two other functions, we calculate the perimeter and the area of the circle:
#include <iostream>
using namespace std;
float pi = 3.14;

float perimeter(float r)
{
    return 2*pi*r;
}

float area(float r)
{
    return pi*r*r;
}

int main()
{
    float rad;

    cout<<"Radius: ";
    cin>>rad;

    cout<<"Perimeter: " << perimeter(rad)<<endl;
    cout<<"Area     : " << area(rad)<<endl;

    return 0;
}
Note that we use the pi variable in functions, without declaring them within their scope.

If we were to use local variables, we would have to declare pi more than once, which would not be very efficient.

Use global variables when they are needed in many different parts of your code.
And you can use the same name for a local and global variable. In this case, the local variable will have priority.

Global constants

Very careful when using global variables. In complex programs, it is easy to 'lose control' of global variables, as they can be changed anywhere in code.

In most cases, give priority to using same arguments.

However, if you want to use global variables that should not be changed, use the const keyword before declaring the variable:
  • const float pi = 3.14;

Let's suppose a hacker broke into your system, and entered a function called change(), which will change the value of pi to 4, sabotaging your project:
#include <iostream>
using namespace std;
const float pi = 3.14;

void change()
{
    pi = 4;
}

int main()
{
    change();

    return 0;
}
As the variable was declared with the const keyword, it will give the error:
"| 7 | error: assignment of read-only variable pi ’|"

That is, the variable is read only, cannot change the 'pi'. And in fact, no program should change pi, so it makes sense that it is global and constant, do you agree?

Let's assume that you will create a system for a large supermarket chain, and you will set the discount price at 10%, do:
  • const float off = 0.1;

Ready. Now thousands of functions can access the discount amount.
What if you want to increase the discount to 20%?
Easy, just do:
  • const float off = 0.2;

See that you changed just one thing, just one variable. But it automatically modified the calculations of the thousands of functions that use this variable directly.

It changes only once, and the change occurs in multiple corners.
If you had done it locally, you would have to go to each function and change variable by variable ... it would take hours or days.

But with constant global variable, no. Changes only once. And everything changes.
Did you get the utility of global and constant variables?

Static local variable

When we declare a variable within a function, it is created and reserved in computer memory at the beginning of the function and is destroyed at the end of the function's execution.

In the code example below, we initialize the myVar variable to 1, print, increment by one, and terminate the function.
#include <iostream>
using namespace std;

void test()
{
    int myVar=1;

    cout<<myVar<<endl;

    myVar++;
}

int main()
{
    test();
    test();

    return 0;
}
We call the test() function twice, and what appears on the screen is always the same: the value 1.

Each time the function runs, the variable is created, initialized and the value 1 is displayed. It is incremented, but then the function ends and the variable simply dies.

We then say that local variables are nonpersistent. That is, they do not 'persist', they are created and destroyed along with the function.

There is a way to make the variable persistent, that is, it is created initially and not destroyed, its address and value in memory still remains. These are the static variables.

To declare a variable to be static, just use the static keyword before the declaration:

  • static int myVar;


Veja:
#include <iostream>
using namespace std;

void test()
{
    static int myVar=1;

    cout<<myVar<<endl;

    myVar++;
}

int main()
{
    test();
    test();
    test();
    test();

    return 0;
}
Ready. No matter how many times you call the test() function, the myVar variable you will use is declared and initialized only once. When the function ends, it will still persist and when calling the function again, it will already take the previous value of the variable, to print and increment.

Like global variables, local static are always initialized to 0 if you do not explicitly initialize. And if you boot, this boot will only occur once, as you saw in the previous code example, ok?

C++ Data Types, Variables, and Attribution: int, char, float, double, and bool

In this tutorial of our C++ course, we will learn how to work with data (information) in programming.

Storing Information

One of the pillars of computing is the storage of information, data.
The computer basically does two things: calculations and data storage.

Almost always, it does both: data processing, like store, change, delete, do math operations, and so on.

In this tutorial, although long is quite simple, we will introduce the concepts of data types and variables in C ++, highly important knowledge for working with computer programming.

Let us know the most varied types of data, their characteristics and functions.
Beforehand, know that every variable you will use to store data throughout your programs must be declared in advance.

Using a variable that has not been declared will result in errors at compile time.

The integer data type: int

This datatype is specifically for storing numeric data of the integer type.
The integers are:
  • ..., -3, -2, -1, 0, 1, 2, 3, ...

Let's now create and declare a variable called age:
  • int age;

Ready. At this point, the computer will take a place from your computer's memory and set it aside for the age variable. And what is stored? Initially, 'junk'.

Let's now assign the value 18 to this variable:
  • age = 18;

Now, whenever we use the number variable, it will be replaced by the integer 18.
Look:

#include <iostream>
using namespace std;

int main()
{
    int age;
    age = 18;

    cout << "My age is: "<< age <<endl;
    return 0;
}

Note that cout does not print the word 'age', but the value contained within this variable.
C++ complete and free tutorial

Character data type: char

In addition to integers, we can also store characters, ie letters.
For this, we use the keyword char (from character).

Let's declare a char variable, named letter.
  • char letter;

Now let's assign a value to it. In this case, as it is a char, we must store some letters of the alphabet, such as C:
  • letter = 'C';

Note that characters must be enclosed in single quotes.
Let's print this letter on the screen:

#include <iostream>
using namespace std;

int main()
{
    char letter;
    letter = 'C';

    cout << "The third letter of the alphabet is: "<< letra << endl;
    return 0;
}

Remembering that 'a' is different from 'A', are two distinct characters.

Characters are most commonly used together, forming text. We will study this in a later section, about Strings, in our course.

Understand:

  • 5 - is a number, a data of type int
  • '5' - is a character, a letter, cannot be used for example in mathematical operations

Floating Data Type: float e double

We have already learned to deal with integers.
However, not everything in life is an integer, like your age.

Often we need to work with fractional values, decimal values.
For this we use the float and double data types:

  • float price;
  • double value;


The difference is that float has single precision, and double has double precision (that is, it fits a larger fractional part, and a larger number of bytes of memory has been reserved for this type of variable).

Let's look at a use:

#include <iostream>
using namespace std;

int main()
{
    float price;
    price = 14.99;

    cout << "Progressive C++ e-book costs: $ "<< price << endl;
    return 0;
}
C++ tutorial


The Boolean data type: bool

You may have heard that in computing (or technology in general) it's all 1 or 0, isn't it?
In fact, the values 1 and 0 are very important because they represent true and false, consecutively.

There is a data type for storing only true / false information (called booleans), bool.
Declaring:

  • bool true;


Assigning a boolean value:

  • truth = true;


Displaying the value of true on screen:

#include <iostream>
using namespace std;

int main()
{
    bool truth;
    truth = true;

    cout << "Truth in C++ is: "<< truth << endl;
    return 0;
}

Results:
C++ tutorial


Exercises:

1. Make a C++ program that displays the value of two Boolean variables, showing each possible assigned value. Use two variables.

2. Redo the previous exercise, now declaring only one variable.

Variables names

Since we have full power to choose the name we want for our variables, we also have some responsibilities.

The first is not to choose keywords, which will be lists in the following topic.
Another responsibility is that of the organization.

You will be tempted to use:
int a, float b, char c

Avoid these names. Use:

int age;
float diameter;
char letter;

That is, variable names that mean something related to the value you will store there. This helps a lot when your programs get bigger and more complex.

Also avoid:
double salaryprogrammer;

Use:
double salary_programmer;

Or yet:
double salaryProgrammer;

Notice how this makes it easier to read and from the start we can already predict what kind of information you have in these variables, do you agree?

Reserved Keywords

There are some words you should not use as names for your variables, as they are reserved for the inner workings of C ++.

Are they:
and, and_eq, asm, auto, bitand, bitor, bool, break, case, catch, char, class, compl, const, canst cast, continue, default, delete, do, double, dynamic_ cast, else, enum, explicit, export, extern, false, float, for, friend, goto, if, inline, int, long, mutable, namespace, new, not, not_ eq, operator, or, or_eq, private, protected, public, reg i ster, reinterpret_cast, return, short, signed, sizeof, static, static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, us ing, virtual, void, volatile, wchart, while, xorxor_eq

Exercise Answer

#include <iostream>
using namespace std;

int main()
{
    bool booleanValue;
    booleanValue = true;
    cout << "Truth in C++: "<< booleanValue << endl;

    vabooleanValuelorBooleano = false;
    cout << "False in C++: " << booleanValue << endl;
    return 0;
}