當前位置:編程學習大全網 - 網絡軟體 - 面試題:C語言用十種方法實現hello world程序,怎麽做?

面試題:C語言用十種方法實現hello world程序,怎麽做?

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;

}

  • 上一篇:新青海拔高度是多少?
  • 下一篇:馬步沖拳與馬步樁區別
  • copyright 2024編程學習大全網