I am just starting to study with ++ and therefore, using the old habit, I index the elements of the array in the manner indicated below, please suggest how to organize the indexing "according to the mind" so that it would look more acceptable to the C language. Thanks in advance.

void Calculations() { int min; int id=0; for (int i=1; i<m; i+=2) { min = matr[i][0]; for (int j=1; j<n; j++) { if (matr[i][j] < min) min = matr[i][j]; } if (min<0){ mas[id]=min;id++; } } 
  • I do not understand the question. Formally, everything seems to be correct. If you add #include <stdio.h> int matr [20] [20], mas [20], m, n; and } at the end, it is generally compiled (g ++). - avp
  • 2
    Garbage told you. Normal style. To work with simple two-dimensional arrays - quite suitable. - skegg
  • five
    > the problem is that the teacher told me then it could serve as a signal to you that you should not trust this teacher unconditionally, and some of his words should be perceived with a reasonable degree of skepticism - DreamChild
  • 2
    It means so. In modern C ++, it is customary to index arrays in a human way: array[index] . “Indexing” by means of address arithmetic ( *(array + index) ) is considered unreadable code and just a bad style. I do not advise adapting to a teacher with a qualification at the level of a freshman. The fact that, in principle, you can write does not mean what you need . There must be very good reasons for writing unreadable code. - VladD
  • one
    > The fact that, in principle, you can write, does not mean that you need a lot of crosses in general, which is generally possible, but unacceptable in or undesirable in real projects - DreamChild

3 answers 3

I would improve a little. Like that:

 void computeSomething() { int min = 0; int id = 0; for (int i = 1; i < m; i+=2) { min = matrix[i][0]; for (int j=1; j < n; j++) { if (matrix[i][j] < min) { // [оптимизация] min = matrix[i][j]; // [оптимизиация] } } if ( min < 0) { result[id] = min; id++; } } 

The rest has not yet decided. Code questions:

  • If they call you when you are at sea and ask "what is m, n, id in your code?". Can you answer without hesitation? Do you have any common names that you always use?
  • Rename the matrix to more meaningful!
  • Rename m, n, id to something adequate

What you did not consider:

  • Min initialization at the very beginning
  • They gave the name to such that when searching for bugs in your code a person tormented himself as much as possible. Imagine that in your company, when the committees in the repository, the full address of the authors and code modifiers is affixed to each source, and that the following programmers will know where to run and use the bat;
  • Not put braces. Even for single actions it matters. Helps with debugging, easy to put printf and bryak;

If you really quite be meticulous to chew on trivial things, then:

  • A piece of code with for (int j .... Can be fully rendered into a separate function, imagine that you are writing a comment. So call it
  • Inside the same code, the section with if (matrix [] [] <min .. to put into a separate method conditionalSomething ();
  • A piece of code with if at the very end is also in a separate method;

The question "Are the min, id right?"

Answer : Yes. They are declared as needed. Metric : as a rule, the variable should be declared within 5 lines, if further, then you have written too many letters and the code should be broken down into smaller functions.

No need to be like the Soviet period and its names "Glavstroynahmash" or "Sovreitrakh" or something else. Write as easy as possible!

PS: About optimization: "matrix [i] [j]", you can pull in: "int * curLine = matrix [i];" Then you can be addressed as: "curLine [j]"

  • one
    The principal mistake of this code and the code of the author of the question is that it is not very easy to use the result of void computeSomething() . - I will explain. As a result, we get an array (result []) of negative minima of odd columns of the matrix. This array is external to the function. But the number of filled elements in it remains inside ( int id local). The only sensible way would be to fill all result elements, for example, with zeros before calling computeSomething() and analyzing it for negative values ​​after the call. - Conclusion: return id! - avp
  • In this case, I preferred not to return the id, for one simple reason, the task of the method is "Calculate" rather than "Return." The fact is that we must strive to describe in one action the relevant level of abstraction to avoid any questions from the reader of the code. If you still want to return, then reflect it in the name of the method for example computeSomethingAndGetId (). You can not force the reader of the code to ask questions "Yes, where does this happen somewhere?". I will say that I am a sinner, I have a lot of guancode too;))) But nevertheless;) - sys_dev
  • @sys_dev, good names, no doubt better than bad ones, but still the quality of the code depends on them not as much as it is presented in books like "Clean Code", "Perfect Code", etc. IMHO is better than any int negminrows(int *matrix, int rows, int cols, int result[]) that is convenient for use than absolutely self-describing itself with one name, but requiring five extra lines of code when working with it (I exaggerate ...) method. - By the way, you noticed that the main problem with the author’s understanding is connected with matrices of unknown dimension during compilation (see comments in the question) - avp
  • @avp, of course drew. The author did not see the problem due to incomprehensible code. We often "seeing a book see a fig." For many years, Reversing-Engineering has become accustomed to experimenting a lot and a lot of things that have been taken on trial from the books of Fowler and McConnela continue to be “tried” until now, going into the category of “Daily Practice”. I recommend to take your code, remove from it any mention of your authorship and go to the guru, whom you highly respect and whose opinion you appreciate. Say that this code contains a bug and does not understand how to fix. Evaluation of your code - the time for which your friend will fix the bug - sys_dev
  • @sys_dev, interesting thoughts :) "Bug" to make or leave the code as it is? And then do not forget the old joke - each corrected error contributes at least one more. - And about “I didn’t see the problem because of an incomprehensible code” (it doesn’t refer to the author), it’s usually the other way around - if a person realizes all the problems, then he writes beautiful code. - avp

read the code below I think you will understand

 int main(){ // ОБЪЯВЛЕНИЕ МАССИВОВ // 1. обычное обьявление int array_one[10][10]; // 2. с использованием макроподстановки (с человеческим лицом) #define FIRST_INDEX 10 #define SECOND_INDEX 10 int array_two[FIRST_INDEX][SECOND_INDEX]; // 3. с использованием констант (C++ метод) const int FIRST_INDEX_CONST = 10; const int SECOND_INDEX_CONST = 10; int array_three[FIRST_INDEX_CONST][SECOND_INDEX_CONST]; // ИСПОЛЬЗОВАНИЕ МАССИВОВ // для работы с индексами массива можно использовать // 1. имена переменных с целым типом или сам литерал (число) int x = 5; array_one[x][5] = 555; // 2. любое выражение возвращающие целое число int y; array_one[x + 1][y = x - 1] = 333; return 0; } 
  • 2
    But for # #define constants in the XXI century, you can (need) be punished. - alexlz
  • one
    I agree, but other people's codes should also be able to read - perfect
  • one
    @alexlz, I remember, I once read a lot about the harm of #define , but something no one could unconditionally convince me of their unconditional harm compared to const . Can you succeed? The main argument against const is that C and C ++ interpret them differently (in the sense of scope when linking several modules). Those. using const completely binds the project to the crosses (with all the flows ...) - avp
  • @avp Well, I didn't even think about the difference in visibility const. The main objection is that the macro processor works up to all controls and parses (including blocks and he doesn't care - he doesn't know them) For example: #include <stdio.h> #define a 1 int main () {{#define a 2} printf ("% d", a); return 0; } (True, gcc warned me. Now. When I stepped on this rake, I did not see the warning or did not notice it). Almost all diagnostics are ignored by the macro processor (and even more so if you use cpp). And then used the protothreads, which are the essence of the macro library. - alexlz
  • @alexlz, of course, the compiler does not know anything about #define , and the debugger (at least gdb) knows nothing about them. And this is natural if they are not considered as part of the language. Just treat them like a preprocessor (i.e., look at what it really is). And plan debugging accordingly. Against enum objections (except that I personally do not remember them well) I just do not have. But problems with linking constants ... - avp

In C and C ++, the first element of the array has an index of 0. And then try to correct your text yourself.

  • > In C and C ++, the first element of the array has an index of 0, and indeed almost everywhere, Pascal’s feed , DreamChild
  • In FORTRAN, it seems, you can even specify the index from which the numbering of the elements of the array begins. - skegg
  • @mikillskegg like starting with f77. In f4, the lower limit of the index was not set and was equal to 1. - alexlz
  • I did not deal with Fortran below f77))) - skegg