1. C++ / Говнокод #27483

    +5

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    #include <unistd.h>
    #include <stdio.h>
    #include <limits.h>
    
    template<size_t Size> struct static_string {char data[Size];};
    template<size_t ... Indexes>struct index_sequence {};
    template<size_t Size, size_t ... Indexes>
    constexpr static_string<sizeof ... (Indexes) + 1> make_static_string(const static_string<Size>& str,index_sequence<Indexes ...>) {return {str.data[Indexes] ..., '\0'};}
    constexpr static_string<1> make_static_string() {return {'\0'};}
    template<size_t Size, size_t ... Indexes>
    struct make_index_sequence : make_index_sequence<Size - 1, Size - 1, Indexes ...> {};
    template<size_t Size>
    constexpr static_string<Size> make_static_string(const char (& str)[Size]) {return make_static_string(str, make_index_sequence<Size - 1>{});}
    template<size_t ... Indexes>
    struct make_index_sequence<0, Indexes ...> : index_sequence<Indexes ...> {};
    template<size_t Size, size_t ... Indexes>
    constexpr static_string<sizeof ... (Indexes) + 1> make_static_string(const char (& str)[Size],index_sequence<Indexes ...>) {return {str[Indexes] ..., '\0'};}
    template<size_t Size>
    constexpr size_t static_string_find(const static_string<Size>& str, char ch, size_t from, size_t nth) {return Size < 2 || from >= Size - 1 ? UINT_MAX :str.data[from] != ch ? static_string_find(str, ch, from + 1, nth) :nth > 0 ? static_string_find(str, ch, from + 1, nth - 1) : from;}
    template<size_t Size>
    constexpr size_t static_string_find_0(const static_string<Size>& str, char ch, size_t from, size_t nth) {return Size < 2 || from >= Size - 1 ? 0 : str.data[from] != ch ? static_string_find_0(str, ch, from + 1, nth) :nth > 0 ? static_string_find(str, ch, from + 1, nth - 1) : from;}
    template<size_t Size1, size_t ... Indexes1, size_t Size2, size_t ... Indexes2>
    constexpr static_string<Size1 + Size2 - 1> static_string_concat_2(const static_string<Size1>& str1, index_sequence<Indexes1 ...>,const static_string<Size2>& str2, index_sequence<Indexes2 ...>) {return {str1.data[Indexes1] ..., str2.data[Indexes2] ..., '\0'};}
    template<size_t Size1, size_t Size2>
    constexpr static_string<Size1 + Size2 - 1> static_string_concat_2(const static_string<Size1>& str1, const static_string<Size2>& str2) {return static_string_concat_2(str1, make_index_sequence<Size1 - 1>{},str2, make_index_sequence<Size2 - 1>{});}
    template<size_t Begin, size_t End, size_t ... Indexes>
    struct make_index_subsequence : make_index_subsequence<Begin, End - 1, End - 1, Indexes ...> {};
    template<size_t Pos, size_t ... Indexes>
    struct make_index_subsequence<Pos, Pos, Indexes ...> : index_sequence<Indexes ...> {};
    template<size_t Begin, size_t End, size_t Size>
    constexpr static_string<End - Begin + 1> static_string_substring(const static_string<Size>& str) {return make_static_string(str, make_index_subsequence<Begin, End>{});}
    template<size_t Begin, size_t Size>
    constexpr static_string<Size - Begin> static_string_suffix(const static_string<Size>& str) {return static_string_substring<Begin, Size - 1>(str);}
    #define remove_underscore(arg) ([] () __attribute__((always_inline)) {constexpr auto a = static_string_find(make_static_string(arg),'_',0,0) == UINT_MAX? make_static_string(arg):static_string_concat_2(static_string_concat_2(static_string_substring<0,static_string_find_0(make_static_string(arg),'_',0,0)>(make_static_string(arg)),static_string_suffix<static_string_find_0(make_static_string(arg),'_',0,0)+1>(make_static_string(arg))),make_static_string("\0"));return a;}().data)
    
    int main()
    {
        puts(remove_underscore("_testtest"));
        puts(remove_underscore("test_test"));
        puts(remove_underscore("testtest_"));
    }

    Убогий constexpr в c++11

    mittorn, 25 Июня 2021

    Комментарии (46)
  2. C++ / Говнокод #27474

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    Game::Game()
    {
        run = true;//флаг признак нажатия кнопки выхода F5
        Matrix = new int* [8];//Поле 64 ячейки - значения 0 - для пустой ячейки, для игрока каждая пешка-шашка от 1 до 9, для компьютера значения в матрице от 10 до 18
        for (int i = 0; i < 8; i++)
            Matrix[i] = new int[8];
        //Квадраты координат нужны чтобы программа знала какие ячейки над указателем мыши, 64 квадрата
        QuadCoorXleft = new int* [8];//каждой ячейки матрицы Matrix соответстует квадрат координат для мыши xleft означает левую координату x
        QuadCoorXright = new int* [8];//xright - правая x
        QuadCoorYdown = new int* [8];//верхняя y координата
        QuadCoorYup = new int* [8];//нижняя y координата
        for (int i = 0; i < 8; i++)
        {
            QuadCoorXleft[i] = new int[8];
            QuadCoorXright[i] = new int[8];
            QuadCoorYdown[i] = new int[8];
            QuadCoorYup[i] = new int[8];
        }
        //Координаты пешек для отрисовки
        ChessX = new double[18];//X
        ChessY = new double[18];//Y
        //Выделяемая пешка ее координаты и значения
        ActiveX = -1;//X
        ActiveY = -1;//Y
        Active = -1;//Value
        firstplayer = true;//флаг того что можете игрок 1й ходить
        secondplayer = false;//флаг того что можете игрок 2й ходить
        ai = new bool[18];//ячейки флаги того что пешка на финишной позиции
        chessai tmp;
        for (int i = 0; i < 18; i++)
        {
            ai[i] = false;
            if (i > 8)
            {
                tmp.ai = ai[i];
                tmp.value = i+1;
                Ai.push_back(tmp);//Вектор с флагами финиша каждой пешки для искуственного интеллекта
            }
        }
        aicountfirstrow = 0;//счетчик кол-ва пешек ИИ(искуственного интеллекта) на верхней строчке(0-я)
        aicountsecondrow = 0;//счетчик кол-ва пешек ИИ на предверхней строчке(1-я)
        aicountthirdrow = 0;//счетчик кол-ва пешек ИИ на предпредверхней строчке(2-я)
    }

    https://github.com/Beginerok/DominiGames/blob/master/Domini/Chess/Chess/Game.cpp

    https://habr.com/ru/post/563398/
    Странные шахматы как тестовое задание

    PolinaAksenova, 18 Июня 2021

    Комментарии (175)
  3. C++ / Говнокод #27471

    +3

    1. 1
    2. 2
    3. 3
    //! Set this value as an empty object.
    /*! \post IsObject() == true */
    GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; }

    Парсер json'ок писали сверхлюди

    https://github.com/Tencent/rapidjson/blob/master/include/rapidjson/document.h#L1188

    mvngr, 16 Июня 2021

    Комментарии (27)
  4. C++ / Говнокод #27462

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    #include <iostream>
    #include <map>
    
    int main()
    {
      std::string name;
      std::map<int, int> m = { {1, 1}, {2, 2} };
      m.erase(m.end());
      std::cout << "Kokoko " << m[1] << std::endl;
    }

    На моем проекте уходит в бесконечный цикл.

    YpaHeLI_, 08 Июня 2021

    Комментарии (58)
  5. C++ / Говнокод #27456

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    // https://llvm.org/doxygen/AArch64AddressingModes_8h_source.html#l00051
    
     /// getShiftName - Get the string encoding for the shift type.
     static inline const char *getShiftExtendName(AArch64_AM::ShiftExtendType ST) {
       switch (ST) {
       default: llvm_unreachable("unhandled shift type!");
       case AArch64_AM::LSL: return "lsl";
       case AArch64_AM::LSR: return "lsr";
       case AArch64_AM::ASR: return "asr";
       case AArch64_AM::ROR: return "ror";
       case AArch64_AM::MSL: return "msl";
       case AArch64_AM::UXTB: return "uxtb";
       case AArch64_AM::UXTH: return "uxth";
       case AArch64_AM::UXTW: return "uxtw";
       case AArch64_AM::UXTX: return "uxtx";
       case AArch64_AM::SXTB: return "sxtb";
       case AArch64_AM::SXTH: return "sxth";
       case AArch64_AM::SXTW: return "sxtw";
       case AArch64_AM::SXTX: return "sxtx";
       }
       return nullptr;
     }

    Хорош ли тот язык, в котором такую херню надо писать?

    Именно поэтому я за гомоиконы.

    j123123, 06 Июня 2021

    Комментарии (56)
  6. C++ / Говнокод #27454

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    #include <iostream>
    using namespace std;
    
    int main() {
    	const char *kakoiBagor = R""""(
    "Какой
    багор )))"
    )"""";
    	cout << kakoiBagor << endl;
    	return 0;
    }

    А вы знали, что в C++ есть ХЕРЕДОК?

    https://ideone.com/5KdJJQ

    3_dar, 04 Июня 2021

    Комментарии (281)
  7. C++ / Говнокод #27450

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    int main(void)
    {
        std::string data = "HELLO WORLD!\n";
        std::transform(
            data.begin(), data.end(), 
            std::ostream_iterator<char>(std::cout, ""),
        std::bind(std::plus<char>(), std::placeholders::_1, 1));
        
        return 0;
    }

    А как сделать это ещё короче?

    digitalEugene, 02 Июня 2021

    Комментарии (10)
  8. C++ / Говнокод #27444

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    template<typename ReturnType, typename... Arguments>
    std::enable_if_t<!std::is_same_v<ReturnType, void>, std::deque<ReturnType>>
    emit(Event<ReturnType, Arguments...>& event, const std::tuple<Arguments...>& args)
    {
    	std::deque<ReturnType> toReturn;
    
    	for (auto&& c : event.subscribers | std::views::values)
    		toReturn.push_back(std::apply(c, args));
    
    	return toReturn;
    }
    
    template<typename ReturnType, typename... Arguments>
    void emit(Event<ReturnType, Arguments...>& event, const std::tuple<Arguments...>& args)
    {
    	for (auto&& c : event.subscribers | std::views::values)
    		std::apply(c, args);
    }

    кодить всё же надо трезвым.

    digitalEugene, 30 Мая 2021

    Комментарии (0)
  9. C++ / Говнокод #27443

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    // https://habr.com/ru/post/550442/
    // Как компилятор C++ находит правильную функцию 
    
    // Вот так компилятор точно определяет, какую функцию следует вызвать:
    // https://hsto.org/webt/mp/tb/5k/mptb5kheibrreqspserc4sfdfrs.png
    
    // Эти шаги закреплены в стандарте C++. Каждый компилятор C++ должен следовать им,
    // и все это происходит во время компиляции для каждого вызова функции. Оглядываясь
    // назад, это очевидно, что должен быть такой алгоритм. Это единственный способ, которым
    // C++ может поддерживать все вышеупомянутые возможности одновременно. Это то, что вы
    // получите, если необходимо объединить их вместе.
    
    // Я предполагаю, что общая цель алгоритма — «делать то, что ожидает программист»,
    // и до некоторой степени он в этом преуспевает. Вы можете довольно далеко зайти,
    // полностью игнорируя этот алгоритм. Но когда вы начинаете использовать все возможности
    // C++, как при разработке библиотеки, то лучше знать эти правила.

    Да, это конечно очень круто, только вот существует примерно 0 компиляторов, которые полностью корректно (т.е. в полном соответствии с Говностандартом) реализуют эту срань с вызовом правильной функции/метода с учетом всей хуйни.

    https://gcc.gnu.org/bugzilla/show_bug.cgi?id=51577 - этот баг висит еще 2011-12-16 и его так никто нихуя не пофиксил

    И в Clang такого рода баги тоже есть.

    j123123, 29 Мая 2021

    Комментарии (429)
  10. C++ / Говнокод #27437

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    _Return_type_success_(return != false) bool CEnumerateSerial::UsingCreateFile(_Inout_ CPortsArray& ports)
    {
      //Reset the output parameter
      ports.clear();
    
      //Up to 255 COM ports are supported so we iterate through all of them seeing
      //if we can open them or if we fail to open them, get an access denied or general error error.
      //Both of these cases indicate that there is a COM port at that number. 
      for (UINT i=1; i<256; i++)
      {
        //Form the Raw device name
        ATL::CAtlString sPort;
        sPort.Format(_T("\\\\.\\COM%u"), i);
    
        //Try to open the port
        bool bSuccess = false;
        ATL::CHandle port(CreateFile(sPort, GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, 0, nullptr));
        if (port == INVALID_HANDLE_VALUE)
        {
          const DWORD dwError = GetLastError();
    
          //Check to see if the error was because some other app had the port open or a general failure
          if ((dwError == ERROR_ACCESS_DENIED) || (dwError == ERROR_GEN_FAILURE) || (dwError == ERROR_SHARING_VIOLATION) || (dwError == ERROR_SEM_TIMEOUT))
            bSuccess = true;
        }
        else
        {
          //The port was opened successfully
          bSuccess = true;
        }
    
        //Add the port number to the array which will be returned
        if (bSuccess)
    #pragma warning(suppress: 26489)
          ports.push_back(i);
      }
    
      //Return the success indicator
      return true;
    }

    некоторые джавамэны вот таким гордятся

    > Internally the code provides 10 different ways (yes you read that right: Ten)

    еще и выложено под ни с чем не совместимой лицензией

    gologub, 23 Мая 2021

    Комментарии (32)