面试题:C语言用十种方法实现hello world程序,怎么做?

如题所述

第1个回答  2020-10-26
1 最经典的“Hello world!”,直接用 printf 输出 “Hello world!”
#include <stdio.h>
#include <iostream>

int main(){

printf("Hello world! "); // 教科书的写法

puts("Hello world!"); // 我最喜欢的

puts("Hello" " " "world!"); // 拼接字符串

std::cout << "Hello world!" << std::endl; // C++风格的教科书写法

return 0;}

2、用宏写的“Hello world!”

“#”可以“提取”参数的名 字,把它变成字符串。

#include <stdio.h>

#define Say(sth) puts (#sth)

int main(){

return Say(Hello world!);

}

3. 断章取义的“Hello world!”

#include <stdio.h>

int main(){
return puts ("Do not say: Hello world! "[12]);

}

4. 退出时运行的“Hello world!”

atexit()注册回调函数。这个函数可以调用多次,最后注册的函数最先执行。
#include <stdio.h>

#include <stdlib.h>
void say(){printf("world! ");}
void sth(){printf("Hello ");}
int main(){
return atexit(say), atexit (sth);
}
5. 读取自己的“Hello world!”
// Hello world!
#include <iostream>

#include <fstream>
#include <string>
int main(){
std::ifstream ifs(__FILE__);
std::string say, some, word;
ifs >> say >> some >> word;
std::cout << some << " " << word;
return 0;
}
6. 话分两头的“Hello world!”
声明一个全局的类的实例,在 main 函数执行之前会调用这个类的构造函数,结束之后则会调用析构函数。
#include <iostream>

class say{
public:say(){std::cout << "Hell";}
~say(){std::cout << "world!";}
}hello;
int main(){
std::cout << "o ";
return 0;
}
7. 传入模板的“Hello world!”
#include <iostream>

template <char * words>
class say{
public:
void operator () (){std::cout << words;}
};
char hello[] = "Hello world!";
int main(){
return say<hello>()(), 0;
}
8. 调用私有函数的“Hello world!”

#include <iostream>

#include <cstddef>

class secret{

private:

virtual void say(){std::cout << "Hello world!";}

};

int main(){

secret word;

(reinterpret_cast<void (*)()>(**(intptr_t**)(&word)))();

return 0;

}

9. 直接修改函数的返回地址
#include <stdio.h>

#include <stdlib.h>
#include <stddef.h>
void say(){
puts("Hello world!");
exit(0);
}
int main()
{
volatile intptr_t a = 0;
volatile intptr_t * p = &a;
*(p + 2) = (intptr_t)say;
*(p + 3) = (intptr_t)say;
return 0;
}
10. 外星人说的“Hello world!”
#include <stdio.h>

void alien_say (char * p){
while (putchar (*(p += *(p + 1) - *p)));
}
int main(){
return alien_say ("BETHO! Altec oh liryom(a loadjudas!) dowd."), 0;
}
相似回答