M
M
michadimin2021-04-04 16:05:59
Programming
michadimin, 2021-04-04 16:05:59

Why use constants to declare the length of an array?

I really can’t understand this and imagine how to use it ... I’ll ask you to give an example if you can.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
HemulGM, 2021-04-04
@michadimin

To be able to change quickly.
More. Here you have declared an array of 20 elements.
Next, you write code where you use the size value, for example, to enumerate elements in a loop.
Type: от 0 до 20 - 1 печатать()and so hundreds of times in the code.
And then you decided to resize the array. So what are you going to do? Search everywhere for the number 20?
While normally people will only change the constant, and the rest of the code will remain unchanged:
от 0 до РАЗМЕР_МАССИВА - 1 печатать()
Of course, you can calculate the size of the array every time in the code and write like this
от 0 до ДлиннаМассива(массив) - 1
: array size is always the same

G
GavriKos, 2021-04-04
@GavriKos

In what language? On the plus side, this allows you to construct an array on the stack (if I'm not mistaken) and conditionally (very conditionally!) Before the start of the main - that's why you need to use constants there so that the amount of allocated memory is rigidly fixed at the project build stage.

V
Vladimir Korotenko, 2021-04-04
@firedragon

This rule is called don't use magic. For example substring(2,37) what do you think this code does? Plus, you were answered above with multiple renames. There is another point related to strings, let’s say you cut off the end of the string, if you don’t correct the length, you will get garbage, and if you have all the code on a constant and the length of the constant is calculated, then everything will be automatically

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question