Y
Y
Yuri Syrovetsky2012-07-24 22:07:19
Programming
Yuri Syrovetsky, 2012-07-24 22:07:19

What tricks do you know?

What nice tricks and neat tricks to help you write code do you know? Only without fanaticism, let's give those that take no more than a second to understand. Well, no more than five to ten seconds in advanced cases.
I will begin.
With initial n >= 0, the loop will be executed n times, decreasing n

while ( n --> 0 )<br>
{ use(n); }<br>

Dictionary as abbreviated switch
result = {<br>
    1: 'I',<br>
    5: 'V',<br>
    10: 'X',<br>
}.get(input, 'default value')<br><br>
# некоторые доводят до<br>
['no', 'yes'][boolean_condition]<br>
# но это уже зло<br>

Double negation as cast to bool
> [0, 1, !!0, !!1]<br>
[ 0, 1, false, true ]<br>
// полезность данного трюка спорная, по-моему, лучше явно приводить<br>

marklarius reminded me about the good old triple xor value exchange
a ^= b, b ^= a, a ^= b;<br>. And Mezomish said that you can’t shorten it to
a ^= b ^= a ^= b;<br>because the value of the variable changes twice within the same expression.
Unary "+" as coercion to number for languages ​​with "magic" automatic conversion of numbers to strings and back (Perl, PHP, JavaScript) Beware! The behavior of the operator differs from parseFloat and even more so from parseInt (JavaScript), you should use it only in cases where you expect only a number from the argument, perhaps in a string, but everything else can be considered an error. Example: but . You can also apply "+" to other entities (thanks to creage ): Aquahawk
+"10" == 10<br>+'1cm' == NaNparseFloat('1cm') == 1
+ new Date() // миллисекунды с начала Эпохи<br>
showed a minipattern - an analogue of return for a block of code
do {<br>
    ...<br>
    if (some condition) {<br>
        result = some_value;<br>
        break;<br>
    }<br>
    ...<br>
} while(false);<br>

OlegTar recalled a remarkable property of logical operations in many languages: the right argument is not evaluated if everything is already clear from the first one. So you can use and ( && ) as an if , and or ( || ) instead of if not .
# остановится на первом неудачном шаге<br>
( doFirstStep() and<br>
  doSecondStep() == 'ok' and<br>
  doThirdStep() == 0 and<br>
  sendReport() )<br><br>
# знаменитая шутка любителей Perl<br>
use Perl or die();<br>

Also, in some languages ​​(Python, JavaScript) the resulting value is equal to the last operand evaluated.
# значение по умолчанию<br>
x = x or -273;<br><br>
# первая непустая строка<br>
'Mr. ' + (firstname or lastname or nickname)<br>

Answer the question

In order to leave comments, you need to log in

15 answer(s)
M
marklarius, 2012-07-24
@marklarius

The coolest trick is to get programmers to document their work ;)

A
Aquahawk, 2012-07-25
@Aquahawk

do { if (some condition){ some code; break; } if (some other condition){ some code; break; } } while(false);
return analog without function

R
roman_pro, 2012-07-25
@roman_pro

For temporary exclusion from compilation of large pieces of C++ code (possibly containing multiline /*...*/ comments), it is convenient to use the preprocessor construct

#if 0
(...some_temporary_removed_code...)
#endif

O
OlegTar, 2012-07-25
@OlegTar

how to change 0 to 1, 1 to 0

$x = 1 или 0
....
$x = 1 - $x;

- sorting, when you need to move the word 'Total' down, I will show for example Javascript, but it is also possible in other languages ​​where you can set a comparison function, for example, in Perl. The example shows that any values ​​can be forced up or down.
[1, 'total', 'abc', 'zzz'].sort(function (a, b) { 
    if (a == 'total') {
        return 1
    }; 
    if (b == 'total') {
        return -1
    }; 
    if (a < b) {
        return -1
    } 
    else if (a > b) {
        return 1
    }; 
    return 0
});

Result:
[1, "abc", "zzz", "total"]
In Javascript and Perl, if the first number is 0, the empty string is null (in Javascript), undef (in Perl)
then replace it with the default value:
var x = null;
var t = x || 5;
t;

5
Be careful, if x = 0, then the last expression will be returned. (Perl 5.10 has a // operator similar to defined $x? $x: 5;)

S
Silver_Clash, 2012-07-24
@Silver_Clash

x = y - 0 + (z - 0); so that it is guaranteed not to get a concatenation :)

M
Mrrl, 2012-07-25
@Mrl

Recently figured out how to count non-zero bits in int:
res=0; while(a){ a&=a-1; res++;}
Then it turned out that it already exists in Hacker's Delight.

J
JustAMan, 2012-07-25
@JustAMan

Here is an interesting implementation of or/and in Python:

def func(a, b):
    print a or b

func(None, 'q')
func(123, 10)
func([1,2,3],'')
func('', {1: 5})

produces:
q
123
[1, 2, 3]
{fifteen}

those. the result of seemingly boolean expressions is actually not boolean at all, but is equal to the last occurrence, according to which the processing of the condition stopped. So "1 and 5" would be "5".
Well, if you need boolean operations (or bitwise) - there are standard for C &, | and ^.

A
Aquahawk, 2012-07-26
@Aquahawk

Also in javascript you can do something like

obj ||= {}

this will create the object if it doesn't exist, and if it does, it will do nothing with it.
And then there's the Duff's Device mega-brain explosion.
strcpy(to, from, count)
register char *to, *from;
register count;
{
    register n = (count + 7) / 8;
    if (!count) return;
    switch (count % 8) {
    case 0: do { *to = *from++;
    case 7:      *to = *from++;
    case 6:      *to = *from++;
    case 5:      *to = *from++;
    case 4:      *to = *from++;
    case 3:      *to = *from++;
    case 2:      *to = *from++;
    case 1:      *to = *from++;
               } while (--n > 0);
    }
}

A
aspect, 2012-08-01
@aspect

I have already collected one here habrahabr.ru/company/intel/blog/108231/?#comment_3423796

S
silvansky, 2012-10-18
@silvansky

Objective-C has a bunch of tricks with runtime: class_addMethod, for example.

C
coffeesmoke, 2012-10-19
@coffeesmoke

Tricks with code are fun for the programmer himself. But if you work in a team or publish source code for everyone, then readability must be put in the foreground, no matter how smart you want to be. The best you can allow is to cast pointers of different types, or memcpy(...). :)

D
Danil Kopylov, 2016-10-05
@lobsterk

A little trick how you can swap two numerical variables without using a third one.

$a = 5;
$b = 7;
$a = $a + $b; // 12
$b = $a - $b; // 5
$a = $a - $b; // 7

C
creage, 2012-07-24
@creage

JS:
checking the position of the occurrence of a
if (~index) { //did } else { //didn't find it }
millisecond with epoch
+ new Date()
and a bunch more, according to JS, on 140 bytes .

A
avn, 2012-08-01
@avn

Here's what I love about C/C++:
#define sizeofarr(ARR) (sizeof(ARR) / sizeof(ARR[0])) ... int arr[23534]; long f; for (f = 0; f < sizeofarr (arr); ++f) { ... }
And it's strange that there is no such thing in the standard

S
Sh0ttky, 2016-10-05
@Sh0ttky

I got myself a repository to record great tricks there.
https://sourceforge.net/p/c-is-freedom/code/ci/mas...
Now there are two versions of si templates. By the way, they are more flexible and understandable than C++ templates.
https://sourceforge.net/p/c-is-freedom/code/ci/mas...
I would be very happy if someone offers a merge with their tricks there.
( fork -> then commit your own to the fork -> merge reguest )
Here's another trick:

/* 
   USAGE: 
   int64_t m = supermax(1, 234234, 35423523, 777); // m = 35423523
*/

#include "stdint.h"
#include "limits.h"

#define NUM_OF_ARGS(...) (sizeof((int64_t[]){__VA_ARGS__})/sizeof(int64_t))

#define supermax(...) _supermax((int64_t[]){__VA_ARGS__}, NUM_OF_ARGS(__VA_ARGS__))
int64_t _supermax(int64_t arr[], int size)
{
    int64_t max = arr[0];

    int i = 0;
    while (i < size) {
        if (arr[i] > max)
            max = arr[i];
        i++;
    }
    return max;
}


#include "stdio.h"

int main()
{
    int64_t x = supermax(1,2,3,4,5);
    printf("%lld\n", x);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question