I would like to know the function of using a name within a vector?
char chave[NUM_LETRAS + 1];
int frequencias[NUM_LETRAS];
int frequencias2[NUM_LETRAS];
char codificado[MAX_STR];
char descrip[MAX_STR];
I would like to know the function of using a name within a vector?
char chave[NUM_LETRAS + 1];
int frequencias[NUM_LETRAS];
int frequencias2[NUM_LETRAS];
char codificado[MAX_STR];
char descrip[MAX_STR];
Usually capitalized names denote constant values, values that will not change in the course of the program, but nothing prevents these values from having a lowercase name as well. It's just a matter of good practice. A brief example of usage:
#define NUM_LETRAS 50
#define num_letras 25
#define MAX_STR 255
#include <stdio.h>
int main() {
/* Aqui, o compilador troca NUM_LETRAS pelo valor definido acima,
* criando um vetor de caracteres de 51 letras (50 + 1)
*/
char chave[NUM_LETRAS + 1];
/* Já aqui, o compilador troca num_letras por 25,
* criando um vetor de caracteres de 26 letras (25 + 1)
*/
char chave2[num_letras + 1];
// O mesmo ocorre aqui
char codificado[MAX_LEN];
/* fgets() lê de uma fonte de entrada de dados
* (no caso 'stdin') o número MAX_STR (255) de letras
* e coloca dentro do vetor 'codificado'.
*/
fgets(codificado, MAX_STR, stdin);
return 0;
}
Constants are useful when the same number that always refers to the same thing during the code is repeated several times. This facilitates changes to the code, rather than looking up all 255 program values that refer to the maximum size of a string, it simply changes the value set to MAX_STR.
As a result, the code becomes more readable, as this solution avoids the use of "magic numbers" (numeric values that nobody knows where it came from and what it refers to), replacing explicit values without description by self-explanatory names.
It seems like you've confused some things. In C / C ++:
Represents the declaration of a foo variable of type t , allocating a continuous address space ), and finally assigning the address of the first position of this vector to the foo variable variable . Next, we will have bar variables of type t foo will be the memory address of the first position of this vector.
In your example:
char chave[NUM_LETRAS + 1];
It means that we have a vector, storing variables of type char, of size NUM_LETRAS + 1
. In this case, the NUM_LETRAS
name probably represents a preprocessor macro defined via #define
( #define NUM_LETRAS 10
for example).
This avoids the declaration of unnecessary positions in a vector, since the user has the option of entering the desired number of spaces. An example would be registering names in a vector:
#include <iostream>
using namespace std;
int main()
{
int tam; // <- variável que armazena o tamanho do vetor.
cout<<"Digite a quantidade de nomes que deseja inserir: ";
cin>>tam; // <- usuário digita a quantidade de posições desejada.
string nomes[tam]; // <- vetor de tamanho definido pelo usuário.
... // segue código.