danistan
danistan

Reputation: 33

What does it mean dead code in programming languages(especially in dart)?

I was following the flutter guide(fileio) of voiderealms(youtube) and i had this problem on the function readfile, the editor says that is dead code but i dont know what does it mean

i have tried to search on the web

String readFile(String file) {
  try {
    File f = new File(file);
    return f.readAsStringSync();
  }
  catch(e) {
    print(e.toString());
  }
}


main(List<String> arguments) {
  String path = 'C:/Users/danis/Desktop';
  String txtFile = 'C:/Users/danis/Desktop/test.txt';
  list(path);

  if(readFile(txtFile, 'Hello World\n', FileMode.APPEND));{
    print(readFile(txtFile));
  }
}

Upvotes: 2

Views: 6893

Answers (3)

Jonas Wilms
Jonas Wilms

Reputation: 138457

Due to the ; after the if the if statement gets seperated from the block ({}), which means that it always gets executed, no matter what the condition says. However that code is not "dead" as it actually gets executed.

What does [...] dead code [/unreachable code] in [a] programming language [mean]?

Dead code is code that is useless, because it will never execute. A function is dead if it is not called anywhere, statements can be dead if they are after a return or throw:

 // 1
 print("alive");
 return;
 print("dead");

 // 2
 if(false) print("dead");

Upvotes: 5

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277527

This is a bit of code that will never be executed because it doesn't make sense.

For instance:

if (false) {
  print("Hello World");
}

In your case you have such warning because you wrote:

if (something);

Notice the ;, it means that there's nothing to execute within the if.

Upvotes: 4

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657871

DartAnalyzer warns about dead code when it can statically deduct that the code will under no circumstances be executed.

int fun() {
  return 5;
  print('x'); // dead code
}

int fun() {
  if(true) {
    print('x'); 
  } else {
    print('y'); // dead code
  } 
}

Upvotes: 2

Related Questions