codeEveryone knows that C++ syntax is more flexible than many other languages are. You can type many confusing, tricky, obfuscated, yet working source codes in C++.

But do you know these syntactic tricks? These may only be syntactic sugars, but I find them very useful, especially in contests where speed is important.

Local array initialization with zero

int someFunction()
{
    int data[100] = {};
}

Array data’s members will be initialized with zero. You save time by not explicitly memsetting it to zero (typing memset(data, 0, sizeof(data));).

Actually it is known as partial array initialization. If the number of initializers are less than the array’s size, then the rest of the array will be assigned zero. Since the above code doesn’t introduce any initializers, all data’s member will be zero.

Integer-to-double conversion

int n = 2, m = 3;
double x = 1.*n / m;

It will convert n to double before dividing it by m. It’s faster to type than (double)n / m;. The converting expression is actually 1.0*n, but you can omit the 0.

XOR swapping

int a = 1, b = 2;
a ^= b ^= a ^= b;

It swaps the values of a and b, called XOR Swap Algorithm. No need to use std::swap() function from STL, if the type is integral (int, short, long, long long etc.) and is not a reference (e.g. can’t be int&).

Inline statements as expression

#include <cstdio>
int N;
printf("%d\n", ({scanf("%d", &N"); N;}));

It will input a number and output it. Not sure whether it is very useful or not. It’s like a lambda expression. This feature is a GCC’s extension.

To use statements as an expression, surround the statements with braces and then parentheses. The last statement in that construct must be an expression, which will act as the value of the entire construct.

Go and try some of these tricks!

  • Share/Bookmark

Enjoyed this article? Subscribe to our RSS feed for free!

Related posts:

3 Responses to “Useful C++ Syntax You May Don’t Know”

visitor says:
November 28, 2009 at 17:55


Even better than
double x = 1.*n / 2;
is
double x = n / 2.0;

At the xor swap you should mention that it doesn’t work when the two variables alias each other (for example when they are references to the same variable).

[Reply]

fushar replies:


Yes, you’re right. But that’s only an example; the 1.*n can work in other circumstances where conversion is required.
And thanks for reminding me about the XOR swap issue :)

[Reply]

McQWZYX says:
December 1, 2009 at 09:47


I prefer
a=(b=(a=b+a,a-b),a-b)

[Reply]

Leave a Reply