g | x | w | all
Bytes Lang Time Link
nanFrom C++11250330T210102Zmovatica
nan240522T073205ZRém
nanIf you need a type alias230616T185506Zc--
nanWhen possible131112T014441ZAlex Git
nan220817T192203Z46303581
nanSome compilers e.g. GCC support multicharacter constants. This can save a few characters when a large integer value is required. Example110128T122627Zmoinudin
nanFunctions in often requires passing a.begin190809T234905ZJayXon
nan210212T072338ZEasyasPi
nanG++ allows for variablesized arrays191203T210113ZVarad Ma
nan191202T075932ZG B
nan190811T222457Zdingledo
nanIf you're doing C++11 or newer which should always be the case now190426T143542Zmovatica
nanIf you want to swap two integer variables a and b then190214T024912Zparth_07
nan180720T082644ZToby Spe
nan171217T155546Zuser2027
nan180330T150854ZYuval Me
nan110424T202802Zdmckee -
nan131114T034034ZStuntddu
nan150510T152027ZHostileF
nan160525T115014Zmichael-
nan160901T125227ZVolAnd
nan140911T110736ZBaldrick
nan#import instead of #include gives you one more byte.160525T200520Zmichael-
008Don't use string""160705T150120Zuser5420
nanInstead of writing big powers of 10160420T223225ZPranjal
nan160217T195133ZMegaTom
nanInstead of using while1150801T002118ZNaCl
nan150524T214004ZLucas
nanSometimes you can save two characters by using the fact that static storage duration variables that especially includes all global scope variables are automatically zeroinitialized at the beginning unlike automatic variables where you have no such guarantee. So instead of140410T195127Zceltschk
nanQuite an obvious one140410T082208Zbrettwhi
nanIf you're willing to use C++0x110713T233013ZMechanic
nan110430T031706ZMateen U

From C++11, a std::string is always zero-terminated. Thus, of all the characters, exactly the last one is falsy. So, these loops are equivalent:

#include<string>
std::string s;

// indexed loop, yielding an index
// ungolfed
for(int i = 0; i < s.size(); i++)
{
    std::cout << s[i];
}

// golfed C++98
for(int i=0;i++<s.size();)std::cout<<s[i];

// golfed C++11
for(int i=0;s[i++];)std::cout<<s[i];

Note, that depending on the surrounding code, the following alternative looping techniques may be more efficient:

// C++11 iterator loop, yielding an iterator
for(auto i=s.begin();i++<s.end();)std::cout<<*i;

// C++11 ranged-for loop, yielding a character
for(auto c:s)std::cout<<c;

The latter work likewise for std::vector.

If you have some variables declared in a row :

int a,b,c,d;

You can access b by (&a)[1], or c by (&a)[2] ...

It can be interesting there :

(i?a:i-1?b:i-2?c:d)=k;
VS
(&a)[i]=k;

You could have declared an array a[4], but if you use a, b, c, d in other ways, it's not always interesting to replace b by a[1], c by a[2]

Moreover, you know that x[y] = *(x+y) = y[x], so :

(i?a:i-1?b:i-2?c:d)=k;
VS
(&a)[i]=k;
VS
i[&a]=k;

If you need a type alias, using is two bytes shorter than #define:

#define T ... // newline
using T=...;

When possible, change && and || to & and | respectively.

When using simple if statements:

if(<condition>)<stuff>;

can be changed to:

<condition>?<stuff>:<any single character variable or literal>;

which saves a character.

It's rather straightforward to cacluate when replacing something with a #define results in shorter code.

#define a blabla

Where a is a single letter name and blabla is the replacement of length \$x\$ has in total \$10+x\$ characters.

If you have \$n\$ times blabla in the code then the #define pays off when

$$10 + x + n < nx$$

With the define you have \$10 + x\$ to define it and \$n\$-times a single character. Without it you have \$n\$-times blabla of length \$x\$. The following table lists how often blabla has to appear given its length for the define to make the code shorter:

\$x\$ \$n\$
2 13
3 7
4 5
5 4

Because the inequality is symmetric, the same table applies when \$n\$ and \$x\$ are swapped, ie if blabla appears \$n = 2\$ times in the code then the define results in shorter code when blabla is of length \$x \ge 13\$. The formula is

$$n > \frac {10 + x} {x - 1}$$

or

$$x > \frac {10 + n} {n - 1}$$

PS: Sometines the single letter named preprocessor symbol has to be followed by a space. This shifts the matters a little towards not using the define, but just a little.

Some compilers (e.g. GCC) support multi-character constants. This can save a few characters when a large integer value is required. Example:

int n='  ';

The value is implementation-specific. Usually the value of 'ab' is 256*'a'+'b' or 'a'+256*'b'. You can specify up to 4 characters between the quotation marks.

Functions in <algorithm> often requires passing a.begin(),a.end() which is really long, instead you can use &a[0],&*end(a) to save a byte or two if a is vector or string.

std::sort(a.begin(),a.end());
std::sort(&a[0],&*a.end());

// with using namespace std;
sort(begin(a),end(a));
sort(&a[0],&*end(a));
```

Use auto instead of complex type names.

This can be done with generic lambdas and C++20 abbreviated function templates

int x(std::set<std::string>y){}
template<class T>int x(T&y){}
int x(auto&y){}
[](auto&x){}

This also allows you to avoid most includes.

Note that g++ on TIO requires -fconcepts.

G++ allows for variable-sized arrays, so there is no need to go through the lengthy pointer-malloc-new stuff.

int* array = new int[array_size];

becomes

int array[array_size];

Saves 9 bytes minimum with int.

When writing a full program you can use argc to initialize an integer variable to 1:

main(a){

is the same as:

main(){int a=1;

Use GCC builtins instead of importing

If you are using a GCC compiler, it sometimes helps to use their builtin functions, such as __builtin_puts or __builtin_clz. For example,

44 bytes:

int main(){__builtin_puts("Hello, world!");}`

50 bytes:

#import<cstdio>
int main(){puts("Hello, world!");}

If you're doing C++11 or newer (which should always be the case now), use auto for complex types, if possible.

Example: 54 Bytes instead of 66

#include<vector>
std::vector<int> f(std::vector<int> l){return l;}
#include<vector>
auto f(std::vector<int> l){return l;}

Also, as performance does not matter, for some challenges a std::list may just do the job for a few bytes less:

#include<list>
auto f(std::list<int> l){return l;}

If you want to swap two integer variables a and b then ,

a^=b^=a^=b;

can be used , saving 5 characters than the standard way

a+=b;
b=a-b;
a-=b;

Use generic lambdas as cheap templates

For types other than int, using them as function arguments can be expensive. However, generic lambdas were introduced (in C++14?) and allow any lambda to be a template - using auto for the argument types can save bytes. Compare:

double f(double x, double y)
[](auto x, auto y)

Generic lambdas are also very convenient for accepting iterators - probably the best way to accept array inputs in C++ is [](auto a, auto z), where a and z are passed as begin() and end() of the array/vector/list/etc.

Shorter header

This is GCC specific, it may be extensible to other compilers.

Precompiled header.

In G++ bits/stdc++.h is the precompiled header consists of all other headers. If you need to import 2 different ones you can just use this.

Shorter header.

This is all headers listed on http://en.cppreference.com/w/cpp/header:

$("#a").text(pako.inflate(atob('eJx9VkuW1DAM3HON2cOGx4o3V8lzK0q3wZ9gy90TTo+dDKCyM710yT9VqWS/2ECuzPzdhO3108vfUeCHGmUWNfJmVSMbsxo5m/VUEutZjaWsTo9NSkYfO/OvouNZDP1U4xqFOHkjNzVORmzU8YXDXcf5ym86lSIwvljBXOmWYtA7evYxbXCEi0aAAl930TM4JdiDSLYV0njQzSQNlA7Ikmy4KuDOJDFB6mGOHoVZHrPeNMsM7LhIBuWQ6C1pvW6Jjd5jKVKSXtII/qwlaIoA0EoAgHYPZy+A2GswDhCWH37tVpmkKShinZWtmzPzomkyyZoAika/GkiBRsUaU7jK5MxJULNexUGkdpaDAgvFcwKKq2Eqx1q4OCDLgOQBsdGbYIGxQV+KM9NdnmvRsgK99vIFZC95QPbSAmSvYEAeA0Jy7QxMNsdvX789RdoFbVh0Jce1+r6roHoYRXC/Fa4NAlxzN67vQXbk/xAfrn7UDEI73UjLXsUI7aXek1cru4dqIQ8Uh4H1Kl4HtRrseB8kpbEyDylg1sH84N1LjG6QY4bNqN604dpU/Ea8y4QJHLAm211jsnLzsJapDGvTaIsduBTdAt5TxTTOsCaDq+rg/Vq2WPwl0FBteQs02tY6zlsWBp++MzNUQDsaG2edNkky2JsOgae7xRe6brA3b9x2P3yqBoaiX2J6mDRP3WOdq2N4nvo3sYSYZm4RfBr/4/ghOF7IKXGOJRFD6lZszfM3p+FsimvdybhmIrQov621ZXoOYtwX/KVACG8BIbw4hPoPSwyzbepO+8txgfYJC/uvCgT7fwgGu08IBPsfEgSH3whEh7cZ6ek/LshQ/3RBdPhsQHR80yA8PtMQPmndqPhpO9Bpn7msI+bEsSfp96ZCYU7diOec+wpPOrckMvaBsz6Y9KS6//Xcp3f62LHdZu9NeFqjs7S9/gHXxXg4'), {to: 'string'}));
<script src="https://cdn.rawgit.com/nodeca/pako/master/dist/pako.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="a">
  
</pre>

sorted in increasing order of length.

Some of them are already longer than bits/stdc++.h, and some of them requires C++17 support. Some others are not supported by TIO G++ (for reasons I don't know of). Filter out them we have:

$("#a").text(pako.inflate(atob('eJx9VcuS3CAMvOc39p5Tak+p/MoUI2SbhIcDYrz++4BdW6WG1B7VYI36IebNRfLV8s/Ix69vb59VYVFVMLuqXCqq8q7oqyQusKql7l7XJmdzqtry36rPixj6o+p2CucUjGyqzkZc0ucLx5c+55U/NJUqUD+dIFfacoq6Y+CQ8gk/4ZMRkCC0LvoG5ww9iOTcgcZBm8kaqANQJLu4KuDFJCkD9WhTQGOWw+qmRSyo4xMZtENScKT92jIb3WOpUrP+pAv8XVvQHQGgRwCAPod3T0DcGo0HhOV32IevTNYSVHHeyTncsbxoZHajqxDBY1MKZ0E/RocmAyiFlmUdnlgDZ5CvLUPTT5uSJmSZkDIhLgUTHagxeUfJMr3ka507K/DiiiYgV5wBuWIDyJVOQI4JIVmH5SRX0vuP9y+RPqCLi06pE25rDVl/GT++HG5W9rYVhrrTgNAlJBK+sofQFdBRlpbHEWrxm8SLk57NlgHq6RoUncyiOXO3yHDr1nTauGdKfhLaQjNqk3Zcrwt/EO/tUY1I4Ia12H5N2ckWkNUc7gt4VljSmxaO/D+sS+6bEzhLZ4YRrpH6yPCifHKbPOwN8cFq1x6SDb4b5SzC4dEWBqK4pHyYbB/DH19p68D2cf+//APa+54V'), {to: 'string'}));
<script src="https://cdn.rawgit.com/nodeca/pako/master/dist/pako.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="a">
  
</pre>

It may happens that some of them can be replaced by shorter ones. Just binary search whether the one you need can be replaced. In particular:

cstdio -> ios        (-3 bytes)
algorithm -> regex   (-4 bytes)
vector -> queue      (-1 byte)
string -> map        (-3 bytes)
bitset -> regex      (-1 byte)
numeric -> random    (-1 byte)

Kind of late to the party I guess...

If you want to turn an expression into -1 and 1 instead of 0 and 1, instead of this:

int x;
if (a * 10 > 5)
    x = 1;
else
    x = -1;

do this:

int x = (a * 10 > 5) * 2 - 1;

It can save some bytes depending on usage.

The ternary conditional operator ?: can often be used as a stand in for simple if--else statements at considerable savings.

It is of special value in that it can be used to select alternate lvalues as in

#include <iostream>
#include <cstdlib>
int main(int c, char**v){
  int o=0,e=0,u;
  while(--c) ((u=atoi(v[c]))%2?o:e)+=u;
  std::cout << "Sum of odds " << o <<std::endl
            << "Sum of evens " << e <<std::endl;
}

Since array elements are stored directly after one another in memory, instead of something like this:

for(int x = 0; x < 25; x++) {
    for(int y = 0; y < 25; y++)
        array[x][y] = whatever;
}

You can do something like this:

int* pointer = array;
for(int i = 0; i < 25*25; i++, pointer++)
    *pointer = whatever;

Obviously neither of the above are golfed, for readability, but explicitly using pointers can save you a lot of space.

Using the comma operator in lieu of open and close braces can save a few characters, if you have a situation where your clauses have more than one statement in them:

if(c){x=1;cout<<"Hi";y=2;}else{x=2;cout<<"Bye";y=3;}

vs.

if(c)x=1,cout<<"Hi",y=2;else x=2,cout<<"Bye",y=3;###

Two characters saved on a plain IF, or three total for an IF/ELSE.

As a point of distinction between C and C++, the result of a comma expression in C++ as a whole may be used as an lvalue...FWIW.

You may use the ternary operator ?: without any expressions in the true-block (it saves a byte)

#include <iostream>

int foo()
{
    std::cout << "Foo\n";
}

int main()
{
    1?foo():0;  // if (true) foo()
    0?:foo();   // if (!false) foo()
}

Check it here

In my first attempt at code golf for task "Subtract the next numbers" I have started from function (58 bytes)

int f(int N, int P){int F;for(F=N;P;F-=++N,P--);return F;}

then safe 5 bytes with shifting to lambda and moving initialization out of for (53)

[](int N,int P){int F=N;for(;P;F-=++N,P--);return F;}

and finally after switching from for to while I got 51 bytes:

[](int N,int P){int F=N;while(P--)F-=++N;return F;}

The ungolfed test code is something like:

#include <iostream>
int main(void)
{
    int N, P;
    std::cin >> N >> P;
    auto f = [](int N,int P)
    {
        int F = N;
        while (P--)
            F -= ++N;
        return F;
    };
    std::cout << f(N, P) << std::endl;
    return 0;
}

UPDATE:

Actually for can reach the same length as while:

[](int N,int P){int F=N;for(;P--;F-=++N);return F;}

One that I found handy:

Taking advantage of the fact that non-zero values evaluate to true in boolean expressions, and that x&&y evaluates to x*y when dealing with booleans

(x!=0 && y!=0)

evaluates to

(x*y)

You just have to be aware of overflows, as pointed out below.

#import instead of #include gives you one more byte.

Also, the space character between #import and header is not necessarily:

#include <map>
// vs
#import<map>

And if you need something from stdlib header, you may import any header with STL container (preferable set or map) instead of cstdlib.

Don't use string(""), use "". It saves 8 bytes.

Instead of writing big powers of 10, use e notation. For example, a=1000000000 is longer than a=1e9. This can be extended to other numbers like a=1e9+24 is better than a=1000000024.

It is useful to remember is that a[i] is the same as *(a+i).

Replace a[0] with *a for two character savings. Also, a[i][0] is equivalent to *a[i] and a[0][i] shrinks down to i[*a]. So if you are hard-coding a 0 index in your array, a better way probably exists.

Instead of using while(1), use for(;;), saving one character :)

Arithmetic operations on Booleans:

Although

a*=b>0?.5:-.5

is better than

if(b>0)a*=.5;else a*=-.5;

it is not as good as

a*=(b>0)-.5

Also, using #define on anything that is used a lot. It is often shorter than using functions, since type names are not necessary.

Combine things as much as possible:

a+=a--;

is the same as

a=2*a-1;

Sometimes you can save two characters by using the fact that static storage duration variables (that especially includes all global scope variables) are automatically zero-initialized at the beginning (unlike automatic variables where you have no such guarantee). So instead of

int main()
{
  int a=0;
  // ...
}

you can write

int a;
int main()
{
  // ...
}

Quite an obvious one, but it you are using a lot of the standard library, using namespace std; might save a few characters.

If you're willing to use C++0x, you can use new features like lambdas.

Use the following types:

u64, s64, u32, s32 (or int)

For repetitive words/types, use #defines:

#define a while

It's only worth it if you use while a lot to make up for the extra 10 characters. (About 4.)