hello world in C without semicolons and without IF/WHILE/FOR statements [closed]

夙愿已清 提交于 2019-12-17 15:26:59

问题


My friend says it's possible to write a C program that will print "hello world" without IF/WHILE/FOR and without semicolons. After minimal research I told her it was not possible. Is it possible?


回答1:


I've been trying to find a "portable" way of stealing a semicolon from an include file. This works under Linux:

int main(int ac, char **av)
{
#define typedef
#define uint8_t a[printf("hello world\n")]
#include <stdint.h>
}

This causes the one typedef unsigned char uint8_t to become my printf.

Another trick that worked was to #define away every standard stdint type such that stdint.h reduces to a bunch of semicolons.

Both of these fall flat on FreeBSD because it uses private intermediate types (like __uint8_t) which means that removing typedef fails in the quoted example and prevents me from successfully removing all non-semicolons in the other case.

It seems like it should be possible to steal a semicolon cleanly from an include file. Can anyone improve on my attempt?




回答2:


#include <stdio.h>

int main() {
    switch (printf("Hello, world!\n")) {}
}

If your friend says "oh, you can't use switch either," then:

#include <stdio.h>

int main(int argc, char *argv[printf("Hello, world!\n")]) {}



回答3:


I'm torn about whether to suggest this because it hinges on the exact wording of the question, but:

#error hello world

(if nothing else, perhaps it will stave off a followup "how do you print hello world without main"...)




回答4:


it's possible to write a C program that will print "hello world" without IF/WHILE/FOR and without semicolons.

Easy. Note that C is case sensitive.

int main()
{
    if (printf("Hello, World\n")){}
}

if is a keyword in C, IF is not.




回答5:


You could also workaround the limitation like

#define X i##f
#define Y whi##le
#define Z f##or
#define W swi##tch



回答6:


What about:

#include <stdio.h>
int main(void *HAHA[printf("Hello world!\n")]) {}

ain't C cool :)




回答7:


you can use switch statement to get your desire output,here is the code below

#include<stdio.h>

int main()
{
  switch(printf("hello world"))

return 0;
}

hope this will help you



来源:https://stackoverflow.com/questions/4147836/hello-world-in-c-without-semicolons-and-without-if-while-for-statements

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!