Java: Subtract '0' from char to get an int… why does this work?

前端 未结 9 665
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 05:04

This works fine:

int foo = bar.charAt(1) - \'0\';

Yet this doesn\'t - because bar.charAt(x) returns a char:

int foo = bar.c         


        
9条回答
  •  孤城傲影
    2020-11-27 05:22

    Your code may compile without error & run without throwing an exception, but converting between char's & int's is bad practice. First, it makes the code confusing, leading to maintenance headaches down the road. Second, clever "tricks" can prevent compilers from optimizing the byte code. One of the best ways to get fast code is to write dumb code (i.e., not clever code).

提交回复
热议问题