- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
#include <stdio.h>
struct{int a; float b;} test()
{
return (typeof(test())){1337, 666.666};
}
int main()
{
auto a = test();
printf("%d %f\n", a.a, a.b);
return 0;
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
Всего: 339
0
#include <stdio.h>
struct{int a; float b;} test()
{
return (typeof(test())){1337, 666.666};
}
int main()
{
auto a = test();
printf("%d %f\n", a.a, a.b);
return 0;
}
В стандарт C23 добавили auto и теперь можно писать такую хуйню. В "Clang" работает: https://godbolt.org/z/GG3addqPb
0
// https://github.com/ggml-org/llama.cpp/blob/f4c3dd5daa3a79f713813cf1aabdc5886071061d/examples/simple/simple.cpp#L23
// parse command line arguments
{
int i = 1;
for (; i < argc; i++) {
if (strcmp(argv[i], "-m") == 0) {
if (i + 1 < argc) {
model_path = argv[++i];
} else {
print_usage(argc, argv);
return 1;
}
} else if (strcmp(argv[i], "-n") == 0) {
if (i + 1 < argc) {
try {
n_predict = std::stoi(argv[++i]);
} catch (...) {
print_usage(argc, argv);
return 1;
}
} else {
print_usage(argc, argv);
return 1;
}
} else if (strcmp(argv[i], "-ngl") == 0) {
if (i + 1 < argc) {
try {
ngl = std::stoi(argv[++i]);
} catch (...) {
print_usage(argc, argv);
return 1;
}
} else {
print_usage(argc, argv);
return 1;
}
} else {
// prompt starts here
break;
}
}
if (model_path.empty()) {
print_usage(argc, argv);
return 1;
}
if (i < argc) {
prompt = argv[i++];
for (; i < argc; i++) {
prompt += " ";
prompt += argv[i];
}
}
}
Парсинг аргументов командной строки
0
typedef struct ll_node
{
struct ll_node *prev;
struct ll_node *next;
int val;
} ll_node;
ll_node a;
ll_node b;
ll_node c = {&a, &b,3};
// не работает
a.next = &b;
a.prev = &c;
b.next = &c;
b.prev = &a;
/*
c.next = &a;
c.prev = &b;
*/
// зато так работает:
ll_node arr[3] = {
{&arr[2], &arr[1],1},
{&arr[0], &arr[2],2},
{&arr[1], &arr[0],3}
};
Кольцевой двусвязный список.
0
// https://godbolt.org/z/f4s13WEWM
#include <inttypes.h>
int test(uint32_t a, uint32_t b)
{
if (a > b)
return a+b;
return a*b;
}
int test2(uint32_t a, uint32_t b)
{
return (a+b)*(a > b) | (a*b)*!(a > b);
}
int test3(uint32_t a, uint32_t b)
{
return
((a+b) & (uint32_t)(!(a > b) - 1)) |
((a*b) & (uint32_t)((a > b) - 1));
}
int test4(uint32_t a, uint32_t b)
{
const uint32_t arr[2] = {a+b, a*b};
return arr[!(a > b)];
}
/* ASM output
test:
bltu a1, a0, .LBB0_2
mul a0, a1, a0
ret
.LBB0_2:
add a0, a0, a1
ret
test2:
bltu a1, a0, .LBB1_2
mul a0, a1, a0
ret
.LBB1_2:
add a0, a0, a1
ret
test3:
bltu a1, a0, .LBB2_2
mul a0, a1, a0
ret
.LBB2_2:
add a0, a0, a1
ret
test4:
addi sp, sp, -16
add a2, a1, a0
mul a3, a1, a0
sltu a0, a1, a0
sw a2, 8(sp)
sw a3, 12(sp)
xori a0, a0, 1
slli a0, a0, 2
addi a1, sp, 8
add a0, a0, a1
lw a0, 0(a0)
addi sp, sp, 16
ret
*/
Наглядная демонстрация того, что компилятор может насрать на ваши попытки заставить его сгенерить branchless машинный код. Получилось это только в "test4"
0
// https://github.com/AlexCeleste/C99-Lambda
// # C99-Lambda: nested functions, lambdas, and closures, in ISO C99
// https://github.com/AlexCeleste/C99-Lambda/blob/57583080392d5f3f626034bbb3292eb0070ba304/c_lambda.h#L110
// Internal lambda builder functions
#define FN_8CL_ARG_TYPE(T) , T
#define FN_8FEXP(call, p, f, R) { FN_8GETTYPE_8fn f = fn f; call(M_ID p M_IF(M_2ORMORE R, (_fun, M_REST_ R), (_fun))); }
#define FN_8CLEXP(call, p, c, R) { void * _fun = cl c; call(M_ID p M_IF(M_2ORMORE R, (_fun, M_REST_ R), (_fun))); }
#define FN_8EMIT_NS(N, H, B, Q) FN_8EMIT_NS_((FN_8GET_NL(N, B)), H, (M_ZIP_W2(FN_8EMIT_ELEM, B, M_ILIST)), Q)
#define FN_8EMIT_NS_(NL, H, BL, Q) (8ZIPNE,(NL, BL, Q), FN_8EMIT_BODY(NL, H, BL))
#define FN_8GET_NL(N, B) M_ZIP_W2(FN_8GET_NL_1, M_ENLIST(_8anon_##N##_, M_NARGS B), M_ILIST)
#define FN_8GET_NL_1(A, B) , M_CONC_(A, B)
#define FN_8EMIT_BODY(NL, H, BL) M_ID H M_ZIP_WITH(FN_8EMIT_BLOCK, BL, NL)
#define FN_8EMIT_ELEM(E, _) ,M_CONC_(FN_8EMIT_, E)
#define FN_8EMIT_8blk(...) (1, 0, __VA_ARGS__)
#define FN_8EMIT_8fn(...) (0, 0, __VA_ARGS__)
#define FN_8EMIT_8cl(...) (0, 1, __VA_ARGS__)
#define FN_8EMIT_BLOCK(P, N) M_IF(M_FIRST P, (M_REST2 P), (FN_8EMIT_NAME((M_REST P, r, a, o), N)))
#define FN_8EMIT_NAME(P, N) M_IF(M_FIRST P, (FN_8EMIT_CL(N, M_ID P)), (N))
#define FN_8EMIT_CL(...) FN_8EMIT_CL_(__VA_ARGS__)
#define FN_8EMIT_CL_(n, _, r, a, o, ...) (void*)&(struct n##_env_t){ \
n,sizeof(struct n##_env_t) M_FOR_EACH(FN_8CL_SND, M_ID o) }
#define FN_8CL_SND(P) , M_REST_ P
#define FN_8EMIT_ENV(E, Q) (8DO_Q, (Q), FN_8EMIT_ENV_(E))
#define FN_8EMIT_ENV_(n, rt, a, o) struct n##_env_t { \
FN_8CTYPE(rt, n, a, _fun); size_t _size; M_FOR_EACH(FN_8FLDS, M_ID o) };
#define FN_8FLDS(F) M_FIRST_ F M_REST_ F;
#define FN_8CL_DEC(rt, n, a) static rt n(void * _envV, M_ID a) { struct n##_env_t * _env = _envV;
#define FN_8FTYPE(rt, C, a, pn) rt(* C pn)a
#define FN_8CTYPE(rt, n, a, pn) rt(* pn)(void *, M_ID a)
#define FN_8FN_TYPE(F) M_CONC(FN_8GETTYPE_, M_FIRST(M_REST((F))))
#define FN_8GETTYPE_8fn(rt, a, ...) rt(* _fun)a
#define FN_8CLSZ(T, N) T M_CONC(_, N);
#define FN_8ZIPNE(NL, BL, Q) (8FLTNE, ((M_ZIP_W2(FN_8ZIPNE_, NL, BL)), Q))
#define FN_8ZIPNE_(N, B) ,(M_FIRST_ B, N, M_REST_ B)
#define FN_8FLTNE(EL, Q) (8POPEM, ((0 M_FOR_EACH(FN_8FLTNE_, M_ID EL)), Q))
#define FN_8FLTNE_(E) M_IF(M_FIRST_ E, (), (,(M_REST_ E)))
#define FN_8POPEM(FL, Q) M_IF(M_2ORMORE(M_ID FL), ((8F2NS, ((M_REST_ FL), Q))), ((8DO_Q, (Q))))
#define FN_8F2NS(FL, Q) (8DO_Q, ((M_FOR_E2(FN_8F2NS_1, M_ID FL), M_ID Q)))
#define FN_8F2NS_1(F) ,FN_8F2NS_2 F
#define FN_8F2NS_2(n, isC, rt, a, ...) M_IF(isC, \
((8EMIT_NS_NX, (n, (FN_8CL_DEC(rt, n, a)), M_REST(__VA_ARGS__))), (8EMIT_ENV,(n, rt, a, M_FIRST(__VA_ARGS__)))), \
((8EMIT_NS_NX, (n, (static rt n a), __VA_ARGS__))))
#define FN_8DO_Q(Q) (M_ID(M_FIRST_ M_FIRST_ Q),(M_ID M_REST_ M_FIRST_ Q, (M_REST_ Q)))
#define FN_8EMIT_NS_NX(...) (8EMIT_NS, (__VA_ARGS__))
Ммм, дерьмецо
0
def neg(x): return int(bin(x)[2:].rjust(8, '0').replace('1','x').replace('0','1').replace('x','0'), 2)
Операция "NEG"
+1
/* Python:
def A004086(n):
return int(str(n)[::-1])
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int A004086(int n) {
char str[12]; // Enough to hold the string representation of an int
sprintf(str, "%d", n);
int len = strlen(str);
char reversed[12];
for (int i = 0; i < len; i++) {
reversed[i] = str[len - 1 - i];
}
reversed[len] = '\0'; // Null-terminate the string
return atoi(reversed);
}
Результат переписывание с "Python" на "C". A004086 это последовательность из OEIS https://oeis.org/A004086
0
// https://github.com/micropython/micropython/blob/1b89c503db690967d50699abe0bfa942f6f6b15e/ports/qemu/mcu/rv32/interrupts.c#L131
const char *lookup_cause(uint32_t mcause) {
if (mcause & 0x80000000) {
switch (mcause & 0x7FFFFFFF) {
case 1:
return exception_causes[1];
case 3:
return exception_causes[2];
case 5:
return exception_causes[3];
case 7:
return exception_causes[4];
case 9:
return exception_causes[5];
case 11:
return exception_causes[6];
default:
return (mcause >= 16) ?
exception_causes[7] :
exception_causes[0];
}
}
switch (mcause) {
case 0:
return exception_causes[8];
case 1:
return exception_causes[9];
case 2:
return exception_causes[10];
case 3:
return exception_causes[11];
case 4:
return exception_causes[12];
case 5:
return exception_causes[13];
case 6:
return exception_causes[14];
case 7:
return exception_causes[15];
case 8:
return exception_causes[16];
case 9:
return exception_causes[17];
case 11:
return exception_causes[18];
case 12:
return exception_causes[19];
case 13:
return exception_causes[20];
case 15:
return exception_causes[21];
default: {
if ((mcause >= 24 && mcause <= 31) ||
(mcause >= 48 && mcause <= 63)) {
return exception_causes[22];
}
return exception_causes[0];
}
}
}
Микропитухон
0
import std.stdio;
import std.conv;
bool[128][128] a;
int pow2(int x) { return x * x; }
string GenPw(string x, string y, string r)
{
return "pow2("~r~") > pow2("~x~") + pow2("~y~")";
}
string GenPat(int x_sz, int y_sz, string x_str, string y_str, string r_str, string pat)
{
string GenCond = "(";
foreach (y; 0 .. y_sz)
foreach (x; 0 .. x_sz)
{
if(pat[(y) * x_sz + x] == '1')
{
if(GenCond == "(") GenCond ~= "\n ";
else GenCond ~= " && ";
GenCond ~= "("~GenPw(to!string(x)~"+("~x_str~")",to!string(y)~"+("~y_str~")",r_str)~")\n";
}
}
return GenCond ~ ")";
}
bool checkCoordNeihb(int x, int y, int r)
{
if (pow2(r) > pow2(x) + pow2(y))
{
/// Паттерн-матчинг, если
/// 111
/// 101
/// 111
/// то пиксель 0
if (
mixin
(
GenPat
(
3,3,
"x-1",
"y-1",
"r",
"111"~
"101"~
"111"))
)
return false;
return true;
}
return false;
}
void drawCircle(ref bool[128][128] a, int x, int y, int r)
{
foreach (iy; y - r .. y + r)
{
foreach (ix; x - r .. x + r)
{
if (checkCoordNeihb(ix - x, iy - y, r))
a[ix][iy] = true;
}
}
}
void main()
{
drawCircle(a, 24, 24, 15);
writeln("\n\n");
foreach (ix; 0 .. 128)
{
foreach (iy; 0 .. 128)
{
write(a[ix][iy] ? '1' : '0');
}
writeln();
}
}
Переписал на "D" https://govnokod.ru/27990#comment1183758
+1
// https://github.com/torvalds/linux/blob/b6dad5178ceaf23f369c3711062ce1f2afc33644/rust/alloc/alloc.rs#L376
pub const fn handle_alloc_error(layout: Layout) -> ! {
const fn ct_error(_: Layout) -> ! {
panic!("allocation failed");
}
fn rt_error(layout: Layout) -> ! {
unsafe {
__rust_alloc_error_handler(layout.size(), layout.align());
}
}
unsafe { core::intrinsics::const_eval_select((layout,), ct_error, rt_error) }
}
// https://github.com/torvalds/linux/blob/b6dad5178ceaf23f369c3711062ce1f2afc33644/rust/kernel/lib.rs#L96-L103
fn panic(info: &core::panic::PanicInfo<'_>) -> ! {
pr_emerg!("{}\n", info);
// SAFETY: FFI call.
unsafe { bindings::BUG() };
// Bindgen currently does not recognize `__noreturn` so `BUG` returns `()`
// instead of `!`. See <https://github.com/rust-lang/rust-bindgen/issues/2094>.
loop {}
}
// https://github.com/torvalds/linux/blob/master/include/asm-generic/bug.h#L51-L68
/*
* Don't use BUG() or BUG_ON() unless there's really no way out; one
* example might be detecting data structure corruption in the middle
* of an operation that can't be backed out of. If the (sub)system
* can somehow continue operating, perhaps with reduced functionality,
* it's probably not BUG-worthy.
*
* If you're tempted to BUG(), think again: is completely giving up
* really the *only* solution? There are usually better options, where
* users don't need to reboot ASAP and can mostly shut down cleanly.
*/
#ifndef HAVE_ARCH_BUG
#define BUG() do { \
printk("BUG: failure at %s:%d/%s()!\n", __FILE__, __LINE__, __func__); \
barrier_before_unreachable(); \
panic("BUG!"); \
} while (0)
#endif
О том, как в ядре Linux говнораст обрабатывает ошибку аллокации