- 1
- 2
- 3
- 4
int i = 10;
while(i --> 0){
print(i);
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+141
int i = 10;
while(i --> 0){
print(i);
}
+130
#include <stdio.h>
int main()
{
int a = 5, b = 6;
void* go;
go = ( a > b )? &&true1: &&false1;
goto *go;
true1:
{
printf("%i > %i\n", a, b);
goto next1;
}
false1:
{
printf("%i <= %i\n", a, b);
}
next1:
a = 7;
go = ( a > b )? &&true2: &&false2;
goto *go;
true2:
{
printf("%i > %i\n", a, b);
goto next2;
}
false2:
{
printf("%i <= %i\n", a, b);
}
next2:
return 0;
}
В GCC есть такой экстеншен http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
Можно в goto передавать переменную и можно работать с адресами меток. В сочетании с тернарной условной операцией, этим можно заменить if
+123
strncpy (szString, GetPropChar(ParentPicture,"Faceplate instance1","IN0_text_ON") , sizeof(szString));
if (strlen(szString)!=0)
{ SetPropBOOL(lpszPictureName, "Input Bit 0" , "Visible", 1);
SetPropBOOL(lpszPictureName, "I_b0" , "Visible", 1);
}
else
{ SetPropBOOL(lpszPictureName, "Input Bit 0" , "Visible", 0);
SetPropBOOL(lpszPictureName, "I_b0" , "Visible", 0);
}
strncpy (szString, GetPropChar(ParentPicture,"Faceplate instance1","IN1_text_ON") , sizeof(szString));
if (strlen(szString)!=0)
{ SetPropBOOL(lpszPictureName, "Input Bit 1" , "Visible", 1);
SetPropBOOL(lpszPictureName, "I_b1" , "Visible", 1);
}
else
{ SetPropBOOL(lpszPictureName, "Input Bit 1" , "Visible", 0);
SetPropBOOL(lpszPictureName, "I_b1" , "Visible", 0);
}
Скрипт для WinCC. И так 8 раз подряд.
Написал начальник отдела разработчиков (Си— не его специализация), как часть большого концептуального объекта, с которым мне и надо работать. А я не могу с этим работать, ощущая вот такие говенные внутренности.
+129
/*
* Пример программы шифрующей данные симметрично по ключу.
*
* Параметры командной строки:
*
* /program_path [source file path] [destenation file path] [key] [type]
*
* [key] - кодовое слово длинной не более 255 символов.
* [key] - принимает два параметра cript и uncript (шифровать/расшифровать)
*
* Пример использования аргументов:
*
* "/home/aleksandr/Рабочий стол/Крипт/s_cript" "/home/aleksandr/Рабочий стол/Крипт/simple_file_1.txt" "/home/aleksandr/Рабочий стол/Крипт/simple_file_2.txt" simplekey cript
* "/home/aleksandr/Рабочий стол/Крипт/s_cript" "/home/aleksandr/Рабочий стол/Крипт/simple_file_2.txt" "/home/aleksandr/Рабочий стол/Крипт/simple_file_3.txt" simplekey uncript
*
* :P
*
*/
#include <stdio.h>
#include <limits.h>
#include <string.h>
void cript_uncript(FILE* src_fp, FILE* dst_fp, char* key_X, char* block, _Bool type)
{
unsigned char i, real;
while((real = fread(block, sizeof(char), UCHAR_MAX, src_fp)) > 0){
for(i = 0; i < real; i++){
if(type == 0)
block[i] = block[i] + key_X[i];
else if(type == 1)
block[i] = block[i] - key_X[i];
}
fwrite(block, sizeof(char), real, dst_fp);
}
}
void generate_key(char* key, char* key_X){
unsigned char len, i, n = 0;
len = strlen(key) - 1;
for(i = 0; i < UCHAR_MAX; i++) {
key_X[i] = key[n];
if(n++ == len) n = 0;
}
}
int main(int argc, char* argv[]){
FILE* src_fp;
FILE* dst_fp;
char key[UCHAR_MAX], block[UCHAR_MAX], key_X[UCHAR_MAX], s[UCHAR_MAX];
char src_path[1024], dst_path[1024];
if(argc < 4){
puts("not enough arguments\n");
return -1;
}
else{
strcpy(src_path, argv[1]);
strcpy(dst_path, argv[2]);
strcpy(key, argv[3]);
strcpy(s, argv[4]);
}
if((src_fp = fopen(src_path, "rb")) != NULL){
if((dst_fp = fopen(dst_path, "wb")) != NULL){
generate_key(key, key_X);
if(strcmp(s, "cript") == 0)
cript_uncript(src_fp, dst_fp, key_X, block, 0);
if(strcmp(s, "uncript") == 0)
cript_uncript(src_fp, dst_fp, key_X, block, 1);
}
else return -1;
fclose(src_fp);
}
else return -1;
fclose(dst_fp);
Пример программы шифрующей данные симметрично по ключу
+122
#if defined(REG_R1) && !defined(NO_GLOBAL_REG_DECLS)
GLOBAL_REG_DECL(StgUnion,R1,REG_R1)
#else
# define R1 (BaseReg->rR1)
#endif
#if defined(REG_R2) && !defined(NO_GLOBAL_REG_DECLS)
GLOBAL_REG_DECL(StgUnion,R2,REG_R2)
#else
# define R2 (BaseReg->rR2)
#endif
#if defined(REG_R3) && !defined(NO_GLOBAL_REG_DECLS)
GLOBAL_REG_DECL(StgUnion,R3,REG_R3)
#else
# define R3 (BaseReg->rR3)
#endif
#if defined(REG_R4) && !defined(NO_GLOBAL_REG_DECLS)
GLOBAL_REG_DECL(StgUnion,R4,REG_R4)
#else
# define R4 (BaseReg->rR4)
#endif
#if defined(REG_R5) && !defined(NO_GLOBAL_REG_DECLS)
GLOBAL_REG_DECL(StgUnion,R5,REG_R5)
#else
# define R5 (BaseReg->rR5)
#endif
#if defined(REG_R6) && !defined(NO_GLOBAL_REG_DECLS)
GLOBAL_REG_DECL(StgUnion,R6,REG_R6)
#else
# define R6 (BaseReg->rR6)
#endif
#if defined(REG_R7) && !defined(NO_GLOBAL_REG_DECLS)
GLOBAL_REG_DECL(StgUnion,R7,REG_R7)
#else
# define R7 (BaseReg->rR7)
#endif
...
Исходник GHC
https://github.com/ghc/ghc/blob/master/includes/stg/Regs.h#L147
+133
void mb_sim_pix(uchar* IN, uchar* OUT, int *WH, int *bSize, int *A, int *pSize, float *threshold){
int pos = mb_calc_pos(A, WH, pSize);
int nPos;
int i, n;
int B[2];
for(n = 0; n < 4; n++){
switch(n){
case 0:
B[0] = A[0] + 1;
B[1] = A[1];
case 1:
B[0] = A[0];
B[1] = A[1] - 1;
case 2:
B[0] = A[0];
B[1] = A[1] + 1;
case 3:
B[0] = A[0] - 1;
B[1] = A[1];
}
if( B[0] >= 0 && B[0] < WH[0] &&
B[1] >= 0 && B[1] < WH[1]){
nPos = mb_calc_pos(B, WH, pSize);
if(mb_val_pix(OUT, &nPos, pSize) == 0){
if(mb_sim_pack(IN, &pos, &nPos, pSize) >= *threshold){
for(i = 0; i < *pSize; i++) OUT[nPos + i] = IN[nPos + i];
mb_sim_pix(IN, OUT, WH, bSize, B, pSize, threshold);
}
}
}
}
}
Тоже самое через if работает, а через switch проваливается на значении 0 все итерации. Почему?
+142
// main.cpp
#include <stdio.h>
#include <stdlib.h>
//...
#include "tcp.h"
//...
#include "tcp.c"
//...
int main(int argc, char ** argv)
{
//...
receive_tcp_message(sock, &tcp_msg);
switch(tcp_msg.type)
{
#include "cases.h"
default:
break;
}
//...
}
Имелась небольшая утилита, написанная матёрым сишником. Имелся еще меньший шаблонный проект для таких утилит, написанный на плюсах с простым makefile. Таким вот нехитрым способом этот сишник влил первое во второе. Он не пользуется makefile, т.к. обычно пишет шелл-скрипт, собирающий весь проект. А еще он знает кучу анекдотов и историй, выпить не дурак и вообще отличный дядька.
+132
#define max 0x08 //Max number of samples to average/filter
#define byte unsigned char
#define word unsigned int
#define dword unsigned long
#define FILTER 0
#define AVG 1
typedef struct {
word reading[max];
word result[max];
} ResultStct;
static ResultStct x;
static char samp = 0;//filter;
const byte filter_mode = FILTER;
extern int avg_result;
void MYfilter(word input_sample)
{
byte j;
dword X;
x.reading[samp] = input_sample;
if(samp>0){
X=0;
for (j=0;j<=samp;j++){
X += x.reading[j];
}
avg_result = (X >> 3) - 0x0200;
}
// Shift array of results if we hit max
if (samp >= max-1) {
for (j=0;j<max-1;j++){
x.result[j] = x.result[j+1];
x.reading[j] = x.reading[j+1];
}
samp = max-1;
}
else
{
samp++;
} //end if (i => max)
Такой вот МОЩНЕЙШИЙ фильтр встретился в одном проекте.
+134
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <inttypes.h>
union Str
{
uint64_t a;
char str[8];
};
int main(void)
{
union Str str;
memcpy( &str.str, "12345678", sizeof(str.a));
str.a = ((str.a & 0x0F000F000F000F00)>>8) +
((str.a & 0x000F000F000F000F)*10);
str.a = 1000000 * ((str.a >> 0 ) & 0xFF) +
10000 * ((str.a >> 16) & 0xFF) +
100 * ((str.a >> 32) & 0xFF) +
((str.a >> 48) & 0xFF);
//little-endian only. Можно переделать под big-endian
printf("%"PRIu64, str.a);
return 0;
}
Байтоебское преобразование строки из 8 цифр(в виде ascii символов) в число
+138
uint32_t multiply (uint16_t a, uint16_t b)
{
return ((a & ( (int16_t)( ( b & (1 << 0) ) << 15 ) ) / ( 1 << 15) ) << 0 ) +
((a & ( (int16_t)( ( b & (1 << 1) ) << 14 ) ) / ( 1 << 15) ) << 1 ) +
((a & ( (int16_t)( ( b & (1 << 2) ) << 13 ) ) / ( 1 << 15) ) << 2 ) +
((a & ( (int16_t)( ( b & (1 << 3) ) << 12 ) ) / ( 1 << 15) ) << 3 ) +
((a & ( (int16_t)( ( b & (1 << 4) ) << 11 ) ) / ( 1 << 15) ) << 4 ) +
((a & ( (int16_t)( ( b & (1 << 5) ) << 10 ) ) / ( 1 << 15) ) << 5 ) +
((a & ( (int16_t)( ( b & (1 << 6) ) << 9 ) ) / ( 1 << 15) ) << 6 ) +
((a & ( (int16_t)( ( b & (1 << 7) ) << 8 ) ) / ( 1 << 15) ) << 7 ) +
((a & ( (int16_t)( ( b & (1 << 8) ) << 7 ) ) / ( 1 << 15) ) << 8 ) +
((a & ( (int16_t)( ( b & (1 << 9) ) << 6 ) ) / ( 1 << 15) ) << 9 ) +
((a & ( (int16_t)( ( b & (1 <<10) ) << 5 ) ) / ( 1 << 15) ) << 10) +
((a & ( (int16_t)( ( b & (1 <<11) ) << 4 ) ) / ( 1 << 15) ) << 11) +
((a & ( (int16_t)( ( b & (1 <<12) ) << 3 ) ) / ( 1 << 15) ) << 12) +
((a & ( (int16_t)( ( b & (1 <<13) ) << 2 ) ) / ( 1 << 15) ) << 13) +
((a & ( (int16_t)( ( b & (1 <<14) ) << 1 ) ) / ( 1 << 15) ) << 14) +
((a & ( (int16_t)( ( b & (1 <<15) ) << 0 ) ) / ( 1 << 15) ) << 15);
}
Умножение двух чисел через битовые маски и сдвиги без условных переходов. Компилятор переведет деление инта на сдвинутую единчку в арифметический сдвиг
Использование ">>" применительно к signed типам - implementation defined http://stackoverflow.com/questions/4009885/arithmetic-bit-shift-on-a-signed-integer/4009922