简体   繁体   中英

Deconstruct a C++ code block from a novice perspective

I am very new to C++ and I am trying to deconstruct someone's code, and I am not quite sure what to Google for, hence I am just going to ask here. This is a second attempt at a question I asked earlier which was poorly posed. Should this one not measure up, please let me know and I shall try to rectify.

Here is a structurally identical MWE, of the piece of code I am trying to understand.

#include <iostream>

using namespace std;


int square(int x){
    // Function that squares without using *
    int result = 0;
    for (int counter = 0; counter < x; ++counter){ 
        result += x;
    }
    return result;
}


int main()
{
    int const D = 4;
    int myArray[D] = {};    // all elements 0 in C++
    char colour[D] = {'c','o','e','g'};   // Initialize String Array
    int AEST = 5; // Initialise AEST
    for (int d =0; d<D; d++){
        if (colour[d]!='c' && colour[d]!='o'){
             double aux= square (d);
             if (aux!=0){
                myArray[d]=aux;
             }else{ 
                return AEST; 
             }
         }
    }
    // Lets see what we achieved.
    for (int d =0; d<D; d++){ 
        cout << myArray[d];
    }
    return 0;
}

Now then, lets crack on with some questions.

Precisely what I do not fully understand is this block:

             }else{ 
                return AEST; 
             }

Please not, AEST is not an error code, it is a numerical value that the code calculates. I have only initialized it here for the purpose of this MWE, but in actuality, it is calculated earlier on in the original code block.

My question is as follows:

The if statement is only true if the colours are not c or o and in which case we square d . In the MWE we square d twice. Hence, is the code then saying that we break out of the loop (with return AEST ) IF we stumble upon a colour that is not c or o ? But if we do break out of the loop under these conditions, why must we return AEST ? It is already initialised AEST=5 earlier on, and nothing we do inside this loop will affect it (remember this block is structurally identical to what I am trying to understand, but obviously not fully identical). This is why I do not understand the else bit.

Again, if there is not enough information, please let me know.

The return AEST part in question exits the main() function. That means the program exits in state 5.

This is done to have some sort of error code detection. For example. If you have various things that can go wrong, you try to retun those with specific codes so you can look up and identify where the problem occured.

It is common to return 0 if everything is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM