Answer the question
In order to leave comments, you need to log in
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>
result = {<br>
1: 'I',<br>
5: 'V',<br>
10: 'X',<br>
}.get(input, 'default value')<br><br>
# некоторые доводят до<br>
['no', 'yes'][boolean_condition]<br>
# но это уже зло<br>
> [0, 1, !!0, !!1]<br>
[ 0, 1, false, true ]<br>
// полезность данного трюка спорная, по-моему, лучше явно приводить<br>
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. +"10" == 10<br>
+'1cm' == NaN
parseFloat('1cm') == 1
+ new Date() // миллисекунды с начала Эпохи<br>
do {<br>
...<br>
if (some condition) {<br>
result = some_value;<br>
break;<br>
}<br>
...<br>
} while(false);<br>
# остановится на первом неудачном шаге<br>
( doFirstStep() and<br>
doSecondStep() == 'ok' and<br>
doThirdStep() == 0 and<br>
sendReport() )<br><br>
# знаменитая шутка любителей Perl<br>
use Perl or die();<br>
# значение по умолчанию<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
The coolest trick is to get programmers to document their work ;)
do {
if (some condition){
some code;
break;
}
if (some other condition){
some code;
break;
}
} while(false);
return analog without function
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
how to change 0 to 1, 1 to 0
$x = 1 или 0
....
$x = 1 - $x;
[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
});
[1, "abc", "zzz", "total"]
var x = null;
var t = x || 5;
t;
5
x = y - 0 + (z - 0); so that it is guaranteed not to get a concatenation :)
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.
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})
q 123 [1, 2, 3] {fifteen}
Also in javascript you can do something like
obj ||= {}
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);
}
}
I have already collected one here habrahabr.ru/company/intel/blog/108231/?#comment_3423796
Objective-C has a bunch of tricks with runtime: class_addMethod, for example.
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(...). :)
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
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 .
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
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 questionAsk a Question
731 491 924 answers to any question