- 1
- 2
- 3
- 4
- 5
- 6
void receivePtrs(void **);
int main() {
L:
receivePtrs((void *[]){ &&L, 0, 0 });
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
void receivePtrs(void **);
int main() {
L:
receivePtrs((void *[]){ &&L, 0, 0 });
}
что делает этот код?
+3
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#define STRING 0
#define INTEGER 1
#define CAT(x,y) x ## _ ## y
#define J(x,y) CAT(x,y)
typedef union
{
char *J(v, STRING);
int J(v,INTEGER);
} Un;
typedef struct
{
uint8_t Obj_t;
Un u;
} Object;
#define IF_INSTOF(var, t, newvar) \
if(var.Obj_t == t) \
{ \
typeof(var.u.J(v,t)) *newvar = &var.u.J(v,t);
int main(void)
{
Object obj1 = {STRING, {.J(v,STRING) = "1"}};
IF_INSTOF(obj1,STRING,str)
printf("String: %s\n", *str);
}
else
{
printf("Not a string\n");
}
Object obj2 = {INTEGER, {.J(v,INTEGER) = 1}};
IF_INSTOF(obj2,INTEGER,i)
printf("Integer: %d\n", *i);
}
else
{
printf("Not an Integer\n");
}
return EXIT_SUCCESS;
}
Вот такие смарткасты через препроцессор.
https://govnokod.ru/27556#comment655527
0
/* https://fstarlang.github.io/lowstar/html/Introduction.html#the-essence-of-low
Consider the following very simple program:
module Intro
module P = LowStar.Printf
module C = LowStar.Comment
module B = LowStar.Buffer
open FStar.HyperStack.ST
open LowStar.BufferOps
let main (): St Int32.t =
push_frame ();
let b: B.buffer UInt32.t = B.alloca 0ul 8ul in
b.(0ul) <- 255ul;
C.comment "Calls to printf are desugared via meta-programming";
let s = "from Low*!" in
P.(printf "Hello from %s\nbuffer contents: %xul\n"
s 8ul b done);
pop_frame ();
0l
....
Once compiled by the KreMLin compiler, we obtain the following C code:
*/
int32_t main()
{
uint32_t b[8U] = { 0U };
b[0U] = (uint32_t)255U;
/* Calls to printf are desugared via meta-programming */
Prims_string s = "from Low*!";
LowStar_Printf_print_string("Hello from ");
LowStar_Printf_print_string(s);
LowStar_Printf_print_string("\nbuffer contents: ");
LowStar_Printf_print_lmbuffer_u32((uint32_t)8U, (uint32_t *)b);
LowStar_Printf_print_string("\n");
return (int32_t)0;
}
Какая-то компилируемая в сишку хренотень с завтипами, разрабатываемая в Microsoft Research
−1
void* execute_thread(void* arg)
{
int i;
int interval;
//Период контроля времени задаётся с точностью в 10мс.
//Контролировать в данной реализации таймера точность в 1мс не имеет смысла,
//так как это почти не возможно и, как правило, не требуется,
//а крутить проверку таймеров с такой частотой только "пожерать" ресурсы процессора.
struct timespec sleep_period = {0,9999999}; //Период, почти 10 мс
do {
for(i=0;i<n_timers;i++){
if(timers[i]->enable == false){
//Если таймер не активный, то присваиваем ему начальное значение
clock_gettime(CLOCK_REALTIME, &timers[i]->time_before);
}
}
//Засыпаем на 10мс
nanosleep(&sleep_period , NULL);
for(i=0;i<n_timers;i++){
if(timers[i]->enable == true){
//Получаем текущее значение времени.
clock_gettime(CLOCK_REALTIME, &timers[i]->time_after);
//Вычисляем прошедшее время ожидания
interval = ((timers[i]->time_after.tv_sec-timers[i]->time_before.tv_sec)*1000000000
+timers[i]->time_after.tv_nsec-timers[i]->time_before.tv_nsec)/1000000;
//Проверяем условие, если ОК, то обновляем время и формируем событие
if(interval >= timers[i]->interval){
clock_gettime(CLOCK_REALTIME, &timers[i]->time_before);
timers[i]->listener->on_time(timers[i]);
}
}
}
} while (terminate == false);
}
https://habr.com/ru/post/569392/
> Объектно-ориентированное программирование на Си без плюсов. Часть 2. Таймер
0
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>
typedef struct list list;
struct list
{
list* next;
uint32_t data;
};
#define ADD_LIST(ptr, val) \
do { \
(ptr)->next = (list *)alloca(sizeof(list)); \
(ptr)->next->data = val; \
(ptr)->next->next = NULL;\
} while (0)
// https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
#define INIT_LIST(val) \
({ \
list *INIT_LIST = (list *)alloca(sizeof(list)); \
INIT_LIST->data = val; \
INIT_LIST->next = NULL; \
INIT_LIST; \
})
int main(void)
{
list *a = INIT_LIST(5);
ADD_LIST(a,10);
ADD_LIST(a->next,15);
ADD_LIST(a->next->next,20);
ADD_LIST(a->next->next->next,25);
ADD_LIST(a->next->next->next->next,30);
for(list *ptr = a; ptr != NULL; ptr = ptr->next)
{
printf("%d ", ptr->data);
}
return EXIT_SUCCESS;
}
А можно ли в крестоговне так сделать без Сишного Препроцессора?
+4
while (1) {
uint16_t state = in(USB_BASE + USB_ISTR);
if (state & 0x8000) {
uint16_t epstat = in(USB_BASE + USB_EP0R);
if (epstat & 0x8000) {
// RX done
if (epstat & 0x0800) {
// setup
if ((usbRead(0x180) == 0x80) && (usbRead(0x181) == 0x06)) {
uint16_t maxlen = (usbRead(0x187) << 8) | usbRead(0x186);
if (usbRead(0x183) == 0x01) {
// send device descriptor
copyToUsb(0x0100, deviceDescriptor, sizeof(deviceDescriptor));
if (sizeof(deviceDescriptor) < maxlen)
maxlen = sizeof(deviceDescriptor);
out(USB_SRAM_BASE + 0x04, 0x9000 + maxlen); // TX count
// STAT_TX=11 (valid)
if ((in(USB_BASE + USB_EP0R) & 0x0010) != 0x0010)
out(USB_BASE + USB_EP0R, 0x0210);
if ((in(USB_BASE + USB_EP0R) & 0x0020) != 0x0020)
out(USB_BASE + USB_EP0R, 0x0220);
} else if (usbRead(0x183) == 0x02) {
// send config descriptor
copyToUsb(0x0100, configDescriptor, sizeof(configDescriptor));
if (sizeof(configDescriptor) < maxlen)
maxlen = sizeof(configDescriptor);
out(USB_SRAM_BASE + 0x04, 0x9000 + maxlen); // TX count
// STAT_TX=11 (valid)
if ((in(USB_BASE + USB_EP0R) & 0x0010) != 0x0010)
out(USB_BASE + USB_EP0R, 0x0210);
if ((in(USB_BASE + USB_EP0R) & 0x0020) != 0x0020)
out(USB_BASE + USB_EP0R, 0x0220);
} else {
// ... и ещё сотня строк в том же духе ...
Иногда в меня вселяется дух PHP...
+1
// https://github.com/shanecoughlan/OpenGEM/blob/ac06b1a3fec3f3e8defcaaf7ea0338c38c3cef46/source/OpenGEM-7-RC3-SDK/OpenGEM-7-SDK/GEM%20AES%20AND%20SOURCE%20CODE/FreeGEM%20AES%203.0%20(source%20code)/GEMEVLIB.C#L143
/*
* Do a multi-wait on the specified events.
*/
WORD
ev_multi(flags, pmo1, pmo2, tmcount, buparm, mebuff, prets)
REG WORD flags;
REG MOBLK *pmo1;
MOBLK *pmo2;
LONG tmcount;
LONG buparm;
LPVOID mebuff;
WORD prets[];
{
QPB m;
REG EVSPEC which;
REG WORD what;
REG CQUEUE *pc;
#if MULTIAPP
WORD evbuff[8];
WORD pid;
SHELL *psh;
LONG ljunk;
pid = rlr->p_pid;
psh = &sh[pid];
if ( psh->sh_state & SHRINK ) /* shrink accessory */
{
if (pr_shrink(pid, TRUE, &ljunk, &ljunk))
ap_exit(TRUE); /* if no swap space terminate acc */
psh->sh_state &= ~SHRINK;
}
#endif
/* say nothing has */
/* happened yet */
what = 0x0;
/* do a pre-check for a */
/* keystroke & then */
/* clear out the forkq*/
chkkbd();
forker();
/* a keystroke */
if (flags & MU_KEYBD)
{
/* if a character is */
/* ready then get it */
pc = &rlr->p_cda->c_q;
if ( pc->c_cnt )
{
prets[4] = (UWORD) dq(pc);
what |= MU_KEYBD;
}
}
/* if we own the mouse */
/* then do quick chks */
if ( rlr == gl_mowner )
{
/* quick check button */
if (flags & MU_BUTTON)
{
if ( (mtrans > 1) &&
(downorup(pr_button, buparm)) )
{
what |= MU_BUTTON;
prets[5] = pr_mclick;
}
else
{
if ( downorup(button, buparm) )
{
what |= MU_BUTTON;
prets[5] = mclick;
}
}
}
/* quick check mouse rec*/
if ( ( flags & MU_M1 ) &&
( in_mrect(pmo1) ) )
what |= MU_M1;
/* quick check mouse rec*/
if ( ( flags & MU_M2 ) &&
( in_mrect(pmo2) ) )
what |= MU_M2;
}
/* quick check timer */
if (flags & MU_TIMER)
{
if ( tmcount == 0x0L )
what |= MU_TIMER;
}
/* quick check message */
if (flags & MU_MESAG)
{
if ( rlr->p_qindex > 0 )
{
#if MULTIAPP
ap_rdwr(MU_MESAG, rlr, 16, ADDR(&evbuff[0]) );
#endif
#if SINGLAPP
Уххх бля
0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
#define width 65
#define height 25
char mas[height][width+1];
typedef struct {
int x, y, w;
} TRocket;
TRocket racket;
typedef struct { float x, y; int ix, iy; float alfa; float speed;} TBall;
TBall ball;
int hitCnt = 0;int maxHitCnt = 0;
void init(int level)
{ for(int w=0; w<width; w++) mas[0][w] = '#'; strncpy(mas[1], mas[0], width) for(int w=1; w < width-1; w++) mas[1][w] = ' '; for(int h=2; h < height; h++) strncpy(mas[h], mas[1], width);
if(level == 1)
{
for(int w=10; w < width-10; w++)
mas[5][w] = '#';
}
}
void show()
{
for(int x=0; x<height; x++)
{
printf("%s", mas[x]); if(x == 3)
printf(" hit: %d", hitCnt);
if(x == 4) printf(" max: %d", maxHitCnt);
printf("\n");
}
}
void initRocket()
{
racket.w = 7;
racket.x = (width - racket.w) / 2;
racket.y = height - 1;
}
void initBall()
{
moveBall(2.0, 2.0);
ball.alfa = -1;
ball.speed = 0.5;
}
void putBall()
{
mas[ball.iy][ball.ix] = '*';
}
void moveBall(float x, float y)
{
ball.x = x;
ball.y = y;
ball.ix = (int)ball.x;
ball.iy = (int)ball.y;
}
void autoMoveBall()
{
if(ball.alfa < 0) ball.alfa += M_PI*2;
if(ball.alfa > M_PI*2) ball.alfa -= M_PI*2;
TBall bl = ball;
moveBall(ball.x + cos(ball.alfa) * ball.speed,
ball.y + sin(ball.alfa) * ball.speed);
if(mas[ball.iy][ball.ix] == '#' || mas[ball.iy][ball.ix] == '@')
{
if(mas[ball.iy][ball.ix] == '@')
ебаный рот!
+2
/*
https://habr.com/ru/post/523688/
Так как мы работаем с макросистемой C/C++, то аналог функций — макрос, этой
абстракцией мы и будем пользоваться. Мы будем передавать идентификатор первого
рекурсивного макроса в следующий рекурсивный макрос, и тот, в свою очередь, по
мере завершения своего исполнения будет передавать поток исполнения в первый
рекурсивный макрос, так называемое продолжение. Нам также понадобиться терминальное
продолжение — ML99_PRIV_REC_STOP — оно будет являться продолжением, поставляющимся
в самый-самый первый рекурсивный макрос, ведь логично, что никуда, кроме как
закончить исполнение программы на данном месте, нам перепрыгивать не нужно. Жилка
двигателя рекурсии — это цепочка из макросов-раскрывателей следующего вида:
*/
#define ML99_PRIV_REC_0(choice, ...) ML99_PRIV_REC_NEXT(1, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_1(choice, ...) ML99_PRIV_REC_NEXT(2, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_2(choice, ...) ML99_PRIV_REC_NEXT(3, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_3(choice, ...) ML99_PRIV_REC_NEXT(4, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_4(choice, ...) ML99_PRIV_REC_NEXT(5, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_5(choice, ...) ML99_PRIV_REC_NEXT(6, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_6(choice, ...) ML99_PRIV_REC_NEXT(7, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_7(choice, ...) ML99_PRIV_REC_NEXT(8, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_8(choice, ...) ML99_PRIV_REC_NEXT(9, choice)(__VA_ARGS__)
#define ML99_PRIV_REC_9(choice, ...) ML99_PRIV_REC_NEXT(10, choice)(__VA_ARGS__)
//...
//И так до 1023:
Интересно, этот чувак сидит на говнокоде?
+3
#include <stdio.h>
#include <stdlib.h>
#define DEREF(x) ({*(x);})
#define PTR(x) ({&(x);})
#define PTR_T(x) typeof(typeof(x) *)
#define DEREF_T(x) typeof( ({typeof(x) DEREF_T; *DEREF_T;}) )
void add5(PTR_T(int) a)
{
DEREF(a)+= 5;
}
int main(void)
{
int a = 0;
printf("%d\n", a);
add5(PTR(a));
printf("%d\n", a);
int b = 5;
PTR_T(b) b_p = PTR(b); // int *
printf("%d\n", DEREF(b_p) );
DEREF_T(b_p) c = 666; // int
printf("%d", c);
return EXIT_SUCCESS;
}
https://govnokod.ru/27476#comment637183
ASD_77:
потому что я люблю Си и С++ но ненажижу * и & ... поэтому я решил исправить этот недочет в мире
Исправил, проверь. Компилится только в GCC, всё-таки Clang не 100% совместим c гнутыми расширениями.