Is it possible to write a program in C without using semicolons?

Yes, it's possible! In this text I will show a set of tricks to do it. I will present this on a simple program that that reads two numbers from STDIN and prints theirs sum to the STDOUT.

Normally I would start this program from declaring two variables:

int a, b;

Unfortunately, there's a semicolon at the end of the line. It can be omitted by using variables already declared for the main function:

int main(int argc, char* argv[])

I will use argc as a and argv[0] as b. Normally, next thing would be reading two values from STDIN and placing them in a and b variables. It could be like this:

scanf("%d%d", &a, &b);

Once again, there's a semicolon! This one can be skipped by using 'if' statement:

if (scanf("%d%d", &a, &b)) {}

The same trick can be used for printing to STDOUT:

if( printf("%d", a + b ) ){}

Above code compiles and works correctly, but normally the main function should return zero if everything went OK:

return 0;

This semicolon can't be avoided by using the trick with 'if' statement, but we other construction can help here:

if(brk(0)){}

That's all, below is full source code:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
    if (scanf("%d%d", &argc, &argv[0])) {}
    if (printf("%d", argc+argv[0])) {}
    if (brk(0)) {}
}

Leave a comment, if you know other interesting riddles or tricks that can be used here!

3 comments:

  1. With all those '(' and ')' it looks like lisp :P

    ReplyDelete
  2. Hello Robert!
    I've lost Your e-mail address, pls write me message mt8505@poczta.fm.
    Take care!
    Marek
    ps. Intentionally I'm not using my full name, cause CIA invigilate all the Internet space.

    ReplyDelete