在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
当前回答
PHP对字符串中数值的处理。详见之前对另一个问题的回答,但简而言之:
"01a4" != "001a4"
如果你有两个包含不同数量字符的字符串,它们不能被认为是相等的。前导零很重要,因为它们是字符串而不是数字。
"01e4" == "001e4"
PHP doesn’t like strings. It’s looking for any excuse it can find to treat your values as numbers. Change the hexadecimal characters in those strings slightly and suddenly PHP decides that these aren’t strings any more, they are numbers in scientific notation (PHP doesn’t care that you used quotes) and they are equivalent because leading zeros are ignored for numbers. To reinforce this point you will find that PHP also evaluates "01e4" == "10000" as true because these are numbers with equivalent values. This is documented behaviour, it’s just not very sensible.
其他回答
在Python中:
>>> x=5
>>> 1<x<10
True
>>> 1<x<3
False
不是一个WTF,但是一个有用的特性。
在JavaScript中:
2 == [2]
//更陌生 2 == [[[2]]]
//和彻头彻尾的坚果 Var a = {"abc": 1}; A [[[["abc"]]]] === A ["abc"];//这也是正确的
幸运的是,stackoverflow.com网站上善良的人们向我解释了这一切:http:/stackoverflow.com/questions/1724255/why-does-2-2-in-javascript
在Java中可以抛出任何可抛出的东西。
class YourBoss extends Throwable {
}
public class Main{
public void main(String[] s) throws YourBoss {
try{
throw new YourBoss();
}catch(Exception e){
}catch(Error e){
}
}
}
这并不是一个真正的语言特性,而是一个实现缺陷:一些早期的Fortran编译器通过使用常量池来实现常量。所有参数都是通过引用传递的。如果你调用一个函数,例如。
f(1)
编译器会将常量池中常量1的地址传递给函数。 如果您为函数中的参数赋值,则会在程序中全局地更改该值(在本例中为1)。引起了一些挠头。
在C语言中,sizeof操作符不计算其实参。这允许编写看起来错误但实际上是正确的代码。例如,给定类型T,调用malloc()的惯用方法是:
#include <stdlib.h>
T *data = NULL;
data = malloc(sizeof *data);
这里,*data在sizeof操作符中不被求值(data是NULL,所以如果它被求值,就会发生糟糕的事情!)。
这使得人们能够编写令人惊讶的代码,无论如何,对于新手来说。请注意,没有哪个头脑正常的人会这么做:
#include <stdio.h>
int main()
{
int x = 1;
size_t sz = sizeof(x++);
printf("%d\n", x);
return 0;
}
输出1,而不是2,因为x永远不会增加。
对于sizeof的一些真正的乐趣/困惑:
#include <stdio.h>
int main(void)
{
char a[] = "Hello";
size_t s1 = sizeof a;
size_t s2 = sizeof ("Hi", a);
printf("%zu %zu\n", s1, s2);
return 0;
}
(只有当人们对数组、指针和操作符感到困惑时才会出现这种困惑。)