「C++」踩坑

因为PAT刷题的缘故,开始再次接触C++.用过OOP语言再回来用C十分不习惯,C++就顺手多了.C没有泛型,字符串也不好用,C++就好多了,STL的容器和模板完美结合,字符串类也堪用.

按照欲抑先扬的套路,下面就该说说缺点了.作为老资历的语言,C++有些部分真是让人摸不着头脑.比如非void函数可以不返回值

1
2
3
4
5
int do_something(int i)
{
int j = i+1;
// returns nothing;
}

我就在这上面被坑了.BST的构建函数忘记返回值,调了一个多小时.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
node* insert(node* root,int data)
{
if(root==nullptr)
{
root = (node*)malloc(sizeof(node));
root->left = nullptr;
root->right = nullptr;
root->data=data;
return root;
}
if(data<root->data)
{
root->left = insert(root->left,data);
} else {
root->right = insert(root->right,data);
}
//return root
//掉了这一句
}

自己的机器上跑一直没问题,一提交就错.抓瞎搞了一个多小时,又被devcpp的智能提示搞得心态爆炸,切换回了Visual Studio开始调试.结果依旧,不过编译的输出里多了一行Warning

1
warning C4715: 'insert': not all control paths return a value

把掉了的return语句加回去,AC了.

StackExchange上有人问了同样的问题

I forgot to write return 'a'; in function and return 0; in main function but its works fine in Code::Blocks.
1
2
3
4
5
6
7
8
9
10
#include <iostream>
using namespace std;
char show()
{
cout<<"this is show function"<<endl;
}
int main()
{
show();
}
i am using Code::Blocks 10.05 in Ubuntu 12.04. Why this happen and why does the same thing cause an error in TURBO C++?

Answer:

1
2
3
If a function is declared to return a value, and fails to do so, the result is undefined behavior (in C++). One possible result is seeming to work, which is pretty much what you're seeing here.
As an aside, in C, you wouldn't actually have undefined behavior -- in C, you get undefined behavior only if you try to use the return value, and the function didn't specify a value to return.

在其他的语言里,一般会直接报错编译失败,在C++里就变成了编译器警告.去devcpp鼓捣了一下,把warning打开了.我要是选个带VS的考场就不用折腾devcpp了.真的难用.

想到初学编程的时候,编辑器和IDE党的圣战.一方说平均水平高,一方说效率高,争起来无休无止的口水战.

不过现在嘛,因为

  1. 好用的IDE成倍提升效率.
  2. IDE降低了上下文切换的开销,但对工具链不熟悉还是会吃亏.

搞熟了工具链的我选择IDE.

不过tab和space的扣税战到现在还没结束,IDE和编辑器的口水战不知道还要打多少年呢