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

CPuzzle

C Problem Overview


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?

C Solutions


Solution 1 - C

#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")]) {}

Solution 2 - C

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?

Solution 3 - C

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"...)

Solution 4 - C

> 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.

Solution 5 - C

You could also workaround the limitation like

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

Solution 6 - C

What about:

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

ain't C cool :)

Solution 7 - C

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex GordonView Question on Stackoverflow
Solution 1 - CcdhowieView Answer on Stackoverflow
Solution 2 - CBen JacksonView Answer on Stackoverflow
Solution 3 - CBen JacksonView Answer on Stackoverflow
Solution 4 - CJeremyPView Answer on Stackoverflow
Solution 5 - CkennytmView Answer on Stackoverflow
Solution 6 - CsteabertView Answer on Stackoverflow
Solution 7 - CZishanView Answer on Stackoverflow