- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
if (cond1)
{
do_shit1();
}
else if (cond2)
{
do_shit2();
}
else if (cond3)
{
do_shit3();
}
else if (cond4)
{
do_shit4();
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
Всего: 338
0
if (cond1)
{
do_shit1();
}
else if (cond2)
{
do_shit2();
}
else if (cond3)
{
do_shit3();
}
else if (cond4)
{
do_shit4();
}
Вот например есть такая вот типичная хуита, предположим что я знаю, что среди этих cond1 cond2 ... только один может быть true, остальные условия всегда будет ложными.
И в этой сраной цепочке из if - else if можно перемещать if блоки без изменения логики. НО в языке Си (да и в C++ я уверен тоже) нет способа сказать компилятору что-то вроде "только одно из условий true, так что ты, сраный компилятор, можешь переделывать эту хуиту, и даже убрать else, если процессор в таком случае (при if(cond1) {do_shit1();}; if(cond2) {do_shit2();}; ... ) будет эту ссанину быстрее обрабатывать".
Какие-нибудь языки программирования такую оптимизацию вообще умеют?
0
https://twitter.com/i_am_romochka/status/986936174538383365
UDP: кинул тебе за щеку
TCP: кинул тебе за щеку, ПРОВЕРЯЙ
А откуда эта хуита с "защекой" пошла? Не с говнокода ли?
−1
Antony Polukhin
in
pro.cxx
Кстати, в EWG одобрили constexpr контейнеры http://open-std.org/JTC1/SC22/WG21/docs/papers/2018/p0784r1.html
так что есть все шансы к С++20 писать:
constexpr std::string result = foo();
t.me/ProCxx
/184343
Mar 16 at 10:47
Library pragmatism
Current implementations of standard libraries sometimes perform various raw storage operations through interfaces other than the standard allocator and allocator traits. That may make it difficult to make the associated components usable in constexpr components. Based on a cursory examination of current practices, we therefore propose to start only with the requirement that the container templates in the [containers] clause be usable in constexpr evaluation, when instantiated over literal types and the default allocator. In particular, this excludes std::string, std::variant, and various other allocating components. Again, it is our hope we will be able to extend support to more components in the future.
With regards to the default allocator and allocator traits implementation, the majority of the work is envisioned in the constexpr evaluator: It will recognize those specific components and implement their members directly (without necessarily regarding the library definition).
We might, however, consider decorating the class members with the constexpr keyword. Also, some implementations provide extra members in these class templates (such as libc++'s allocator_traits<A>::__construct_forward ) that perform non-constexpr-friendly operations (memcpy, in particular). Lifting such members to standard status would help interoperability between library and compiler implementations.
+6
https://www.opennet.ru/opennews/art.shtml?num=48234
Создатели редактора кода Atom из компании GitHub развивают новый
экспериментальный текстовый редактор Xray, который также построен
с использованием фреймворка Electron, но примечателен тем, что для
повышения надёжности и производительности ядро редактора с
реализацией базовой логики написано на языке Rust, интерфейс
оформлен на JavaScript/CSS с применением фреймворка React, а для
отрисовки текста применяется WebGL.
Чем вообще руководствуются люди, делающие IDE из кусков браузера? Нахрена там JavaScript/CSS, нахрена там React? Еще и Rust приплели зачем-то.
Может это чтоб всякие фронтенд-разрабы возрадовались, потому что теперь их умение писать хуиту на жабаскрипте применимо для написания говноплагинов к этой хуите? А как же бекенд? Пусть дополнительно встроят туда PHP MySQL чтоб никто не ушел обиженным.
+2
// https://github.com/Samsung/ADBI/blob/3e424c45386b0a36c57211da819021cb1929775a/idk/include/division.h#L138
/* Long division by 10. */
static unsigned long long int div10l(unsigned long long int v) {
/* It's a kind of magic. We achieve 64-bit (long) division by dividing the two 32-bit halfs of the number 64-bit
* number. The first (most significant) half can produce a rest when dividing, which has to be carried over to the
* second half. The rest_add table contains values added to the second half after dividing depending on the rest
* from the first division. This allows evaluation of a result which is almost correct -- it can be either the
* expected result, or the expected result plus one. The error can be easily detected and corrected.
*/
/* one dream */
static unsigned long long int rest_add[] = {
0x00000000, 0x1999999a, 0x33333334, 0x4ccccccd, 0x66666667,
0x80000001, 0x9999999a, 0xb3333334, 0xcccccccd, 0xe6666667
};
/* one soul */
unsigned long long int a = div10((unsigned int)(v >> 32));
unsigned long long int b = div10((unsigned int)(v & 0xffffffff));
/* one prize */
int ri = (v >> 32) - a * 10;
/* one goal */
unsigned long long int ret = (a << 32) + b + rest_add[ri];
/* one golden glance */
if (ret * 10L > v) {
//printf("OGG %llu %llu\n", ret * 10, v);
--ret;
}
/* of what should be */
return ret;
}
Деление на 10. Но зачем? Неужели компилятор настолько туп, что сам не может этого сделать?
И да, эти туповатые комментарии one dream, one soul это отсылка к песне Queen - A Kind of Magic https://youtu.be/0p_1QSUsbsM
0
// http://www.compiler.su/prodolzhenie-tsikla-i-vykhod-iz-nego.php
// В PHP выход из вложенного цикла выглядит, на мой взгляд, значительно элегантнее. После «break» указывается количество вложенных циклов, которые должен «покинуть» оператор «break». В приведённом примере, который аналогичен приведённому выше для Java, «break» должен «пересечь» две фигурные скобки «}», чтобы оказаться за пределами двух циклов.
for($i=0; $i < $Imax; ++$i)
{
// ...
for($j=0; $j < $Jmax; ++$j)
{
// ...
if(условие)
break 2;
// ...
}
// ...
}
Интересно, а почему б нечто подобное не сделать для функций? Ну например есть функция a() которая вызывает функцию b() которая вызывает функцию c(), которая вызывает функцию d(), и например в функции d() чтоб сделать особый return_3, который бы вернул управление на три уровня вниз, сразу в функцию a()? Хотя не, хуйня, надо ведь еще знать, какой там тип возвращается в функцию a() из функции b().
То ли дело ассемблер. Можно тупо отмотать стек в нужное место
0
// enum_helper_pre.h
#ifndef delimiter
#define delimiter ,
#endif
#ifndef enumeration_begin
#define enumeration_begin(arg) enum arg {
#endif
#ifndef enumeration_end
#ifdef last_enumerator
#define enumeration_end delimiter last_enumerator }
#else
#define enumeration_end }
#endif
#endif
#ifndef declare_member
#define declare_member(arg) arg
#endif
#ifndef member_value
#define member_value(arg) = arg
#endif
// enum_helper_post.h
#undef delimiter
#undef enumeration_begin
#undef enumeration_end
#undef last_enumerator
#undef declare_member
#undef member_value
// color.h
#include "enum_helper_pre.h"
enumeration_begin(color)
declare_member(RED) member_value(-2) delimiter
declare_member(GREEN) delimiter
declare_member(BLUE) member_value(5) delimiter
declare_member(BRIGHTNESS)
enumeration_end;
#include "enum_helper_post.h"
// main.cpp
#include <iostream>
#include <string>
#include <boost/bimap.hpp>
#include <boost/preprocessor/stringize.hpp>
#include "color.h"
int main(int argc,char* argv[])
{
typedef boost::bimap<color,std::string> map_type;
map_type color_map;
#define declare_member(arg) color_map.insert( map_type::value_type(arg,BOOST_PP_STRINGIZE(arg)) )
#define delimiter ;
#define enumeration_begin(arg)
#define enumeration_end
#define member_value(arg)
#include "color.h"
std::cout<<color_map.left.at(RED)<<std::endl;
std::cout<<color_map.left.at(BLUE)<<std::endl;
std::cout<<color_map.right.at("GREEN")<<std::endl;
std::cout<<color_map.right.at("BRIGHTNESS")<<std::endl;
return 0;
}
// Output
RED
BLUE
-1
6
Нарыл эту хуйню на http://www.quizful.net/post/enum-types-c
0
https://github.com/SeleniumHQ/selenium/commit/388793a775aea41533fb5816aabe710e1b42ff61
+ if (Math.random() > 0.8) {
+ throw new SeleniumError("Selenium 1.0 (Core, RC, etc) is going away; update to WebDriver now.");
+ }
+
0
/*
* Returns 1 if filename has .zip extension.
*/
static int
str_zipext(char *name)
{
int i;
i = strlen(name) - 1;
if (i < 0 || name[i] != 'p' && name[i] != 'P') return 0;
i--;
if (i < 0 || name[i] != 'i' && name[i] != 'I') return 0;
i--;
if (i < 0 || name[i] != 'z' && name[i] != 'Z') return 0;
i--;
if (i < 0 || name[i] != '.') return 0;
i--;
if (i < 0) return 0;
return 1;
}
https://github.com/fabiensanglard/xrick/blob/239d213f01be8d0086c449080ce61bde8dcad7b4/src/data.c#L189
+1
template < typename T >
T shit (void)
{
return 0;
}
int main()
{
int crap = shit();
// Почему дедукция аргумента шаблона в данном случае не работает?
return crap;
}
//-------------------------------------
int shit (void)
{
return 0;
}
// Почему functions that differ only in their return type cannot be overloaded
double shit (void)
{
return 0;
}
int main()
{
int crap = shit();
return crap;
}
Почему плюсы такое говно?