"Hello World" Function Without Using C Printf

How to print Hello in C without using a semicolon?

As long as main is declared with a type compatible with int, it will return 0 at the last } if there is no explicit return statement:

C Standard, § 5.1.2.2.3, Program Termination:

If the return type of the main function is a type compatible with int, a return from the initial call to the main function is equivalent to calling the exit function with the value returned by the main function as its argument; reaching the } that terminates the main function returns a value of 0.

So this code will work:

#include <stdio.h>

int main()
{
if(printf("Hello"))
{

}
}

The real question is why you would want to write a program without semicolons. IOCCC submissions are usually a bit more involved than just that.

Printing a number without using *printf

If your libc contains an itoa() function, you can use it to convert an integer to a string.

Otherwise you'll have to write the code to convert a number to a string yourself.

itoa() implementation from C Programming Language, 2nd Edition - Kernighan and Ritchie page 64:

/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
int i, sign;

if ((sign = n) < 0) /* record sign */
n = -n; /* make n positive */
i = 0;
do { /* generate digits in reverse order */
s[i++] = n % 10 + '0'; /* get next digit */
} while ((n /= 10) > 0); /* delete it */
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}

To print something without using cout, printf or puts()

If you want portability across all standards compliant C++ implementations, you can print a string to standard output in the following ways

const char * str = "Hello World\n";
fprintf(stdout, str);
fputs(str, stdout);
for (int i=0; str[i]!=0; ++i)
putchar(str[i]);
for (int i=0; str[i]!=0; ++i)
putc(str[i], stdout);
for (int i=0; str[i]!=0; ++i)
fputc(str[i], stdout);
fwrite(str, sizeof(*str), strlen(str), stdout);

Additionally, you can use std::cerr and std::clog. They write to stderr instead of stdout, but from the user's perspective, that's often the same place:

std::cerr << str;
std::clog << str;

From an efficiency perspective, I doubt any of these are going to help you. For that purpose, you might want to look at something a bit more platform specific. For POSIX systems, see the answer given by Dave S. For Windows, see this link.

What you shouldn't do, is open up your header files and imitate what they use. At least, not at the middle levels, where they are using different various obscure functions within their own implementation. Those functions might not exist upon the next release. However, if you go to the deepest levels, you will find OS specific calls like the ones in the link I provided above. Those should be safe to use as long as you stay on the same OS, or even between OS versions.



Related Topics



Leave a reply



Submit