Tips for Code Golf


What is Code Golf?

Code golfing is the art of creating a specific program using a minimum amount of characters (or bytes). This should serve as a basic guide for general tips that will shorten the source code of your program in C and C++.

Below is an example of a regular FizzBuzz program:

#include <iostream>

int main(int argc, char *argv[])
{
  for (int i = 1; i <= 100; i++)
  {
    if (i % 3 == 0 && i % 5 == 0)
    {
      std::cout << "FizzBuzz";
    }
    else if (i % 3 == 0)
    {
      std::cout << "Fizz";
    }
    else if (i % 5 == 0)
    {
      std::cout << "Buzz";
    }
    else
    {
      std::cout << std::to_string(i);
    }
    std::cout << std::endl;
  }

  return 0;
}

Here is my attempt to golf FizzBuzz in C++.

#include <cstdio>
int i;main(){for(;++i<101;puts(i%5?"":"Buzz"))printf(i%3?i%5?"%d":"":"Fizz",i);}

Code Golfing Tips in C and C++

The following tips were tested using GCC version 12.2.0.

1. Use the ternary operator

if(condition_a)
{
   statement_1;
   statement_2;
}
else if(condition_b)
{
   statement_3;
}

The ternary operator a ? b : c can save significant amount of characters compared to regular if-else branches.

condition_a?statement_1,statement_2:statement_3;

For example:

int a = 1;
int b = true ? a=2,3: a=5;

After execution, a=2 and b=3. If you’re confused about the comma, look at #2.

2. Use the comma operator

Commas are rarely used in regular programming but extremely useful in code golf. Statements separated by a comma will be executed sequentially. The last statement in any sequence separated by a comma will be the return value of that entire statement.

int a=5,b=0;
b=(a++,do_something(),a-4); // a is now 6, b is now 2
b=a++,do_something(),a-4; // a is now 7, b is now 6

Be careful with operator precedence, in the second example (third line), the first statement being executed is b=a++ because the assignment has precedence over the comma.

3. Use the appropriate printing function

It’s important to use the appropriate printing function to save the most amount of characters. Here’s an overview:

puts takes a C string as an argument and prints it to console with a newline character at the end.

printf takes a C string with format specifiers and additional arguments to format the string appropriately. It does not include a newline character. Note that the program still compiles if some provided arguments remain unused.

printf(i%2?"%d":"even",i);

std::cout takes types supported by the output stream operator. It does not include a newline character.

4. Using the smallest main function

Both in C and C++, the following can be removed from the main function:

  • The return type
  • The return statement
  • The function parameters
// minimal C++ program
#include <cstdio>
main(){puts("Hello World!");}

In C (not in C++), some of the basic includes can be omitted with GCC. Therefore the minimum C “Hello World!” program is the following:

// minimal C program
main(){puts("Hello World!");}

5. Zero-initialize using global variables

Since the address of global variables is known and fixed, the compiler will set their value to zero by default. This is in contrast to local variables that would need their values to be set to zero at runtime, thus it is useful to use global variables in code golf.

int i; // guaranteed to be zero
bool j[9]; // all these will be false
int main(int argc, char**argv)
{
  int k; // probably not zero
  bool l[9]; // unlikely to be all false
}

6. Use bitwise operators for boolean conditions

Bitwise operators can be used to substitute logical operators to save a character.

Here’s how some logical operators can be replaced:

  • a != b becomes a ^ b
  • a && b becomes a & b
  • a || b becomes a | b

Note that both sides of the condition will be evaluated unlike && and ||. The && operator short-circuits when an operand is false and the || short-circuits when an operand is true.

7. Declare multiple variables of the same type on the same line

Multiple variables of the same type may be declared on the same line. Alternatively, an array may be used to store the values.

int a=1,b=2,c=5,d=8,e=9;
int z[5]={1,2,5,8,9};

A significant drawback of declaring all the variables using an array is that at least 2 characters are required to access an element of the array (*z for the first element and at least 4 for any other access i.e z[n]).

8. Use the #define macro

Defining a macro is quite costly in terms of characters, but if you find yourself repeating the same characters, the #define macro can be quite powerful. Note that a #define macro is shorter than a function with arguments.

#define X(a,b) a|b?printf("%d",b+5):b=3; // this is shorter
void f(int a,int& b){a|b?printf("%d",b+5):b=3;}

9. Use the argument count to get a free variable initialized at 1

The following trick only works in C.

main(i){ // i is 1 (the argc value)
    for(;i<101;i++)printf("%d",i);
}

Two program arguments are normally passed to the main function int argc and const char** argv. The number of arguments and their values. When the program is launched without any program arguments, the value of int argc is 1, because the only program argument is the filename. This can be used to avoid initializing a variable.