跳到正文

算法·理论

关于c++主函数那些事

阳宇涵2513约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年3月9日
更新
2026年6月4日
篇幅
约 4 分钟

版本

  1. v1当前

本文章主要讲了神奇的递归,最短的代码,消失的main和程序错在主函数的事

一.这是什么递归

也许本人实力太差,不知道这种递归,勿喷

递归就是一个函数里面套一个和自己一样的函数,然后有一道题求阶乘,一年前学递归的时候做的,老师当时要求用递归,下面是我原来的代码

C++
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll ans = 1;
ll jc(ll x, ll y)
{
	if(x == 1 || x == 0) return 1;
	ans *= (++y);
	if(x == y) return ans;
	jc(x, y);
	return ans;
}
int main()
{
	ios::sync_with_stdio(0);
	ll n, cur = 1;
	cin >> n;
	cout << n << "!=";
	cout << jc(n, cur) << endl;
	return 0;
}

然后今天我突发奇想,是不是所有函数都可以递归?于是自己手敲了一个递归还真过了!!!

C++
#include<bits/stdc++.h>
#define ll long long
using namespace std;
ll n = 1, j, cur = 1, cnt = 0, k;
int main()
{
	ios::sync_with_stdio(0);
	if(n == 1) {cin >> j; k = j;j --;}
	j --;
	n *= (++cur);
	if(j != 0) main();
	if(++cnt == 1) printf("%lld!=%lld", k, n);
	return 0;
}

终于知道主函数可以递归了

二.最简短的代码

主函数名字叫做main,所以编译器必须要扫到main这个单词,然后假如没扫到大概率就会报错,那能不能骗过编译器呢?我们只需要开一个数组就行了

C++
int main[1];

你会发现你编译运行几乎在一瞬间就完成了,这个还有进阶版,在数组里边的数可以用16进制变成代码正常运行,这个我不太了解,感兴趣的可以查一下

三.没有main的程序

前面说了没有主函数大概率会报错,其实还有一种方法不写主函数main,需要头文件

C++
#include<windows.h>

或者

C++
#include<bits/stdc++.h>

然后以a+b为例

C++
#include<bits/stdc++.h>
using namespace std;
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
	int a, b;
	cin >> a >> b;
	cout << a + b << endl;
    return 0;
}

四.程序报错在主函数

如果你的编译器上写的“::main must return”int””请检查你写的是不是”int main”,假如是,请检查你是否写了define int然后主函数写的int,给一个错误示范

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int main()
{
	ios::sync_with_stdio(0);
	return 0;
}

解决方法:

1.把#define int 改为其他的

C++
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main()
{
    ios::sync_with_stdio(0);
	return 0;
}

2.改掉主函数的int

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
signed main()
{
	ios::sync_with_stdio(0);
	return 0;
}

如果觉得还可以,求点赞

原文