- 1
- 2
- 3
bool CheckRepeat(int cur, int i, char* word) {
return (word[cur] != '\0') ? ((word[i] != '\0') ? ((word[cur] == word[i] && cur != i) ? true : CheckRepeat(cur, i + 1, word)) : CheckRepeat(cur + 1, 0, word)) : false;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
−1
bool CheckRepeat(int cur, int i, char* word) {
return (word[cur] != '\0') ? ((word[i] != '\0') ? ((word[cur] == word[i] && cur != i) ? true : CheckRepeat(cur, i + 1, word)) : CheckRepeat(cur + 1, 0, word)) : false;
}
Функция проверки слова на повторение букв.
Задали в институте лабу, в требование входили рекурсия и экономия строк, подпрограммы такого плана понравились преподавателю.
−1
#include <iostream>
#include <string>
using namespace std;
struct A
{
uint16_t n;
uint8_t a1:1;
uint8_t a2:1;
uint8_t a3:1;
uint8_t a4:1;
uint8_t a5:4;
uint8_t b;
} __attribute__((packed));
int main()
{
char v[] = { 0x1, 0x1, 0b01010011, 0x9 };
A *p = (A*)v;
cout << (uint16_t)p->a1 << endl;
cout << (uint16_t)p->a2 << endl;
cout << (uint16_t)p->a3 << endl;
cout << (uint16_t)p->a4 << endl;
cout << (uint16_t)p->a5 << endl;
cout << (uint16_t)p->b << endl;
}
http://cpp.sh/6e5myf
Битовые поля неправильно считываются.
0
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define SIMPLIFY ^ -1
globalStorage[] = {3, 1819043146, 1998597229, 1684828781, 35, 0 };
int* localStorage = globalStorage + 1;
declarator(x) int x; { return x; }
main(void)
{
int* __L_LOCAL_BUF = malloc(-(localStorage[-1] SIMPLIFY) << 2);
for(localStorage[-(localStorage[-1] SIMPLIFY)] ^= localStorage[-(localStorage[-1] SIMPLIFY)];
localStorage[-(localStorage[-1] SIMPLIFY)] <
-(localStorage[-1] SIMPLIFY); ++localStorage[-(localStorage[-1] SIMPLIFY)])
__L_LOCAL_BUF[ localStorage[-(localStorage[-1] SIMPLIFY)]] =
localStorage[localStorage[-(localStorage[-1] SIMPLIFY)]]
^ (((2 * 2 * 2 * 2 * 2 * 2 * 2 *
((int_fast8_t*)((int_fast64_t)(declarator)-(-((-((2ll * 2ll * 2ll * 2ll * 2ll *
2ll * 2ll * 2ll * 2ll) ^ -1ll))
^ -1ll))))[0]) >> 1 >> 2 >> 3) /
((int_fast8_t*)((int_fast64_t)(declarator)-(-((-((2ll * 2ll * 2ll * 2ll * 2ll * 2ll *
2ll * 2ll * 2ll) ^ -1ll))
^ -1ll))))[0]);
printf("%s\n", (const char*)__L_LOCAL_BUF);
free(__L_LOCAL_BUF);
return 0;
}
Переписал Hello world под современные тренды и библиотеки.
0
#include <iostream>
using namespace std;
struct Foo {char a; int b; char c;};
struct Bar {char a; char b; int c;};
int main() {
cout << sizeof(Foo) << endl;
cout << sizeof(Bar) << endl;
}
https://ideone.com/XKWey3
Какой бароп )))
0
Node* reverse(Node* head)
{
Node *end = head, *current = head;
while (end->next != nullptr) {
end = end->next;
}
Node *initial_end = end, *temp = nullptr, *temp_2 = nullptr;
end->next = current;
temp = current;
current = current->next;
temp->next = nullptr;
while (current != initial_end) {
temp_2 = initial_end->next;
initial_end->next = current;
temp = current;
current = current->next;
temp->next = temp_2;
}
return initial_end;
}
Я где-то прочитал, что на собесе нужно написать переворот односвязного списка за 5 минут... Спустя 2 дня получилось это.
0
class std::unordered_map<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,
enum REG,struct std::hash<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,
struct std::equal_to<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > >,
class std::allocator<struct std::pair<class std::basic_string<char,struct std::char_traits<char>,
class std::allocator<char> > const ,enum REG> > > registers"
(?registers@@3V?$unordered_map@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@W4REG@@U?$hash@V?$
basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@2@U?$equal_to@V?$basic_string@DU?$char_traits@D@std@@V?
$allocator@D@2@@std@@@2@V?$allocator@U?$pair@$$CBV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@W4
REG@@@std@@@2@@std@@A) уже определен в decoder.obj PVC-16 C:\Users\Люда\source\repos\PVC-16\PVC-16\interrupt.obj 1
Похлопаем visual c++ за понятный лог.
0
#include <cstdlib>
#include <chrono>
#include <iostream>
#include <thread>
int p = 0;
int *q = nullptr;
void g()
{
using namespace std::chrono_literals;
std::cout << "g()" << std::endl;
std::cout << "g(): p = 1" << std::endl;
p = 1;
std::this_thread::sleep_for(1s);
if (q != nullptr) {
std::cout << "g(): *q = 1" << std::endl;
*q = 1;
} else {
std::cout << "g(): q == nullptr" << std::endl;
}
}
void f()
{
using namespace std::chrono_literals;
std::cout << "f()" << std::endl;
if (p == 0) {
std::cout << "f(): first loop start" << std::endl;
while (p == 0) { } // Потенциально конечный
std::cout << "f(): first loop end" << std::endl;
}
int i = 0;
q = &i;
std::cout << "f(): second loop start" << std::endl;
while (i == 0) { } // Потенциально конечный, хотя в условии только автоматическая пельменная
std::cout << "f(): second loop end" << std::endl;
}
int main()
{
using namespace std::chrono_literals;
std::cout << "f() thread start" << std::endl;
auto thr1 = std::thread(f);
thr1.detach();
std::this_thread::sleep_for(1s);
std::cout << "g() thread start" << std::endl;
auto thr2 = std::thread(g);
thr2.detach();
std::this_thread::sleep_for(2s);
std::cout << "Done" << std::endl;
std::_Exit(EXIT_SUCCESS);
}
Ожидание:
f() thread start
f()
f(): first loop start
g() thread start
g()
g(): p = 1
f(): first loop end
f(): second loop start
g(): *q = 1
f(): second loop end
Done
0
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <conio.h>
const int x_size(20), y_size(10); int x_pos(x_size/2+1); int y_pos(y_size/2+1);
enum border_types{lineNL, single, singleNL};
enum directions{UpLeft=1, UpRight, DownLeft, DownRight}dir;
void draw_border(enum border_types borders) {
do{
if(borders == single || borders == singleNL) break;
for(int i=0; i<x_size+1; i++)
putchar('#');
}while(false);
putchar('#');
if(borders == singleNL || borders == lineNL) std::cout << '\n';}
void display_update() {
system("cls");
draw_border(lineNL);
for(int i=1; i<=y_size; i++)
{
draw_border(single);
for(int j=1; j<=x_size; j++)
{
if(j == x_pos && i == y_pos)
{
putchar('x');
continue;
}
putchar(32);
}
draw_border(singleNL);;
}
draw_border(lineNL);
std::cout << "X: " << x_pos << "\tY: " << y_pos;}
void logic() {
switch(x_pos)
{
case 1:
if(dir == UpLeft) dir = UpRight;
if(dir == DownLeft) dir = DownRight;
break;
case x_size:
if(dir == UpRight) dir = UpLeft;
if(dir == DownRight) dir = DownLeft;
}
switch(y_pos)
{
case 1:
if(dir == UpLeft) dir = DownLeft;
if(dir == UpRight) dir = DownRight;
break;
case y_size:
if(dir == DownLeft) dir = UpLeft;
if(dir == DownRight) dir = UpRight;
}}
void move() {
switch(dir)
{
case UpLeft:
x_pos--;
y_pos--;
break;
case UpRight:
x_pos++;
y_pos--;
break;
case DownLeft:
x_pos--;
y_pos++;
break;
case DownRight:
x_pos++;
y_pos++;
}}
int main() {
srand(time(0));
rand();
switch(rand()%4+1)
{
case UpLeft:
dir = UpLeft;
break;
case UpRight:
dir = UpRight;
break;
case DownLeft:
dir = DownLeft;
break;
case DownRight:
dir = DownRight;
}
while(!kbhit())
{
display_update();
logic();
move();
}
return 0;}
Сорян, пришлось уплотнить фигурные скобки, чтобы код уместился в 100 строк.
0
class UnitedFigure : public Figure {
Figure &f1;
Figure &f2;
public:
UnitedFigure (Figure &_f1, Figure &_f2) : f1(_f1), f2(_f2) {}
double distance_to(const Point &p) const override {
return std::min(f1.distance_to(p), f2.distance_to(p));
}
}
Завезли ссылочные поля класса, это в каком стандарте?
Даже тестил когда то такое, наверное на C++03 и получал ошибку компилятора.
Я и не знал, что добавили такую прекрасную возможность выстрелить себе в ногу.
0
uint64_t stored_msg_id = _container_msg_id.get(ctrl_msg.sequence); // Получаем msg_id из мапы для связки сообщений
if (stored_msg_id)
proto_fill(ctrl_msg, stored_msg_id); // если он там был то новому сообщению даем этот msg_id
else
proto_fill(ctrl_msg); // Иначе формируем новый msg_id
// Отсылаем сообщение
...
// Если msg_id не был в _container_msg_id то произойдет попытка вставки msg_id полученного через proto_fill.
if (!stored_msg_id && !_container_msg_id.insert(ctrl_msg.sequence, ctrl_msg.msg_id))
{
DEBUG(L, 0, "[%p] Can't store request's control message id (%llu) in bunch map" \
", response's msg_id will differ", this, msg.msg_id);
}
С точки зрения читабельности кода, в последнем ветвлении говнокод?