N
N
netrox2016-08-16 12:13:06
C++ / C#
netrox, 2016-08-16 12:13:06

Can you help me figure out the code?

using System;
class FailSoftArray {
int[] a; 
public int Length;  
 
public bool ErrFlag;  
 
public FailSoftArray(int size)
{
    a = new int[size];
    Length = size;
}
 
public int this[int index] 
{
 
get {
        if(ok(index)) {
        ErrFlag = false;
        return a[index];
    } 
    else 
    {
        ErrFlag = true;
        return 0;
    }
}
 
set {
    if(ok(index)) {
    a[index] = value;
    ErrFlag = false;
}
else ErrFlag = true;
}
}
 
private bool ok(int index) {
if(index >= 0 & index < Length) return true;
return false;
}
}
 
class FSDemo {
static void Main() {
    FailSoftArray fs = new FailSoftArray(5);
    int x;
   
    Console.WriteLine("Скрытый сбой.");
    for(int i=0; i < (fs.Length * 2); i++)
    fs[i] = i*10;
    for(int i=0; i < (fs.Length * 2); i++) {
    x = fs[i];
    if(x != -1) Console.Write(x + " ");
}
 
 
 
Console.WriteLine("\nСбой с уведомлением об ошибках.");
for (int i=0; i < (fs.Length * 2); i++) {
//fs[i] = i * 10;
if(fs.ErrFlag)
Console.WriteLine("fs[" + i + "] вне границ");
}
for(int i=0; i < (fs.Length * 2); i++) {
x = fs[i];
if(!fs.ErrFlag) Console.Write(x + " ");
else
Console.WriteLine("fs[" + i + "] вне границ");
}
}
}

If you leave a commented line, then you get the wrong output.
89fa9c468dcc4ca2b6cf192fa53547d1.PNG
What it should be:
9819c18e0c374bc99eaa81d9783b51e9.PNG
Why is this happening?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Ananiev, 2016-08-16
@netrox

Because you have the ErrFlag flag set after assigning a value to an array element, roughly speaking, when the code is executed,
the ErrFlag flag is set to true or false, depending on whether index i has gone beyond the array boundary or not. When you comment this line, ErrFlag retains the last value set to it (true in your case)

N
netrox, 2016-08-16
@netrox

032822642bf44a19947f68ba7b14e714.PNG
Question on this line

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question