在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
在你看来,你遇到过的最令人惊讶、最怪异、最奇怪或最“WTF”的语言特性是什么?
请每个回答只回答一个特征。
当前回答
在JavaScript中:
var something = 12;
function nicelyCraftedFunction()
{
something = 13;
// ... some other code
// ... and in Galaxy far, far away this:
if( false ) // so the block never executes:
{
var something;
}
}
nicelyCraftedFunction(); // call of the function
通常你会期望某个变量的值是13。 但在JavaScript中不是这样——变量有函数作用域,所以后面的声明会影响上游的一切。
在使用C/ c++ /Java表示法的语言(如JS)中,你会期望变量具有块范围,而不是像这样…
因此,编译器甚至可以从最终生成的字节码中删除的死代码块仍然会对正常执行的其余代码产生副作用。
因此,在调用函数之后,某些东西仍然是12 -不变的。
其他回答
在PHP中
var_export('false' == 0); // true
var_export('false' == true); // true
var_export('false' == false); // false
EDIT
正如@Kobi提到的,这可能发生,因为语言将任何值解释为“TRUE”,除了“FALSE”,但在PHP中不是这样,在那里事情比你想象的更奇怪!
这个案例在PHP手册的“字符串转换到数字”一章中有完整的记录,它说:
如果字符串以valid开头 数值数据,这就是值 使用。否则,该值为0 (零)。
这里有一个例子:
print (int) 'zero'; // 0
print (int) 'false'; // 0
// but
print (int) '1 - one'; // 1
附注:我认为这种隐式类型转换弊大于利。
Haskell's use of Maybe and Just. Maybe a is a type constructor that returns a type of Just a, but Maybe Int won't accept just an Int, it requires it to be a Just Int or Nothing. So in essence in haskell parlance Just Int is about as much of an Int as an apple is an orange. The only connection is that Just 5 returns a type of Maybe Interger, which can be constructed with the function Just and an Integer argument. This makes sense but is about as hard to explain as it can theoretically be, which is the purpose of haskell right? So is Just really JustKindaLikeButNotAtAll yea sorta, and is Maybe really a KindaLooksLikeOrIsNothing, yea sorta again.
-- Create a function that returns a Maybe Int, and return a 5, which know is definitly Int'able
> let x :: Maybe Int; x = 5;
<interactive>:1:24:
No instance for (Num (Maybe Int))
arising from the literal `5' at <interactive>:1:24
Possible fix: add an instance declaration for (Num (Maybe Int))
In the expression: 5
In the definition of `x': x = 5
> Just 5
Just 5
it :: Maybe Integer
-- Create a function x which takes an Int
> let x :: Int -> Int; x _ = 0;
x :: Int -> Int
-- Try to give it a Just Int
> x $ Just 5
<interactive>:1:4:
Couldn't match expected type `Int' against inferred type `Maybe t'
In the second argument of `($)', namely `Just 5'
In the expression: x $ Just 5
In the definition of `it': it = x $ Just 5
祝你好运读到这篇文章,我希望它是正确的。
不知道它是否可以被认为是一种语言特性,但是,在c++中,几乎任何与模板相关的编译器错误都会每天向世界各地的许多c++程序员交付相当数量的WTF:)
我喜欢在C中插入八进制值:
int values[8] = { 123, 154, 103, 310, 046, 806, 002, 970 };
我喜欢Smalltalk中缺少运算符优先级
2 * 3 + 4 * 5 = 6 + 4 * 5 = 10 * 5 = 50
而不是
2 * 3 + 4 * 5 = 6 + 4 * 5 = 6 + 20 = 26
这是由于smalltalk的对象性质和消息从左向右传递的事实。如果消息*以数字3作为参数发送给2,则该消息的响应为6。太棒了,如果你觉得邪恶,你甚至可以用猴子来修补它。