- 1
- 2
- 3
- 4
switch (true)
{
}
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
+1
switch (true)
{
}
+1
#include <stdio.h>
#include <stdlib.h>
void myfree(void *ptr)
{
printf("%p\n", *(void **)ptr);
free(*(void **)ptr);
printf("freed!\n");
}
int main(void) {
char *x __attribute__ (( cleanup (myfree) )) = malloc(1);
printf("%p\n", x);
return 0;
}
https://gcc.gnu.org/onlinedocs/gcc/Common-Variable-Attributes.html
cleanup (cleanup_function)
The cleanup attribute runs a function when the variable goes out of scope. This attribute can only be applied to auto function scope variables; it may not be applied to parameters or variables with static storage duration. The function must take one parameter, a pointer to a type compatible with the variable. The return value of the function (if any) is ignored.
If -fexceptions is enabled, then cleanup_function is run during the stack unwinding that happens during the processing of the exception. Note that the cleanup attribute does not allow the exception to be caught, only to perform an action. It is undefined what happens if cleanup_function does not return normally.
+4
#include <inttypes.h>
auto a(auto b) __attribute__ ((noinline));
auto a(auto b)
{
return b*1.5;
}
double test1(double in)
{
return a(in);
}
uint64_t test2(uint64_t in)
{
return a(in);
}
/*
https://godbolt.org/z/6ZQAnv
auto a<double>(double):
mulsd xmm0, QWORD PTR .LC0[rip]
ret
test1(double):
jmp auto a<double>(double)
auto a<unsigned long>(unsigned long):
test rdi, rdi
js .L5
pxor xmm0, xmm0
cvtsi2sd xmm0, rdi
mulsd xmm0, QWORD PTR .LC0[rip] # хули ты мне плавучего питуха в xmm0 возвращаешь?
ret
.L5:
mov rax, rdi
and edi, 1
pxor xmm0, xmm0
shr rax
or rax, rdi
cvtsi2sd xmm0, rax
addsd xmm0, xmm0
mulsd xmm0, QWORD PTR .LC0[rip]
ret
test2(unsigned long):
sub rsp, 8
call auto a<unsigned long>(unsigned long)
movsd xmm1, QWORD PTR .LC1[rip]
comisd xmm0, xmm1
jnb .L8
cvttsd2si rax, xmm0 # ну нахуй тут надо double в uint64_t конвертить
add rsp, 8 # почему это не делается в auto a<unsigned long>(unsigned long)
ret
.L8:
subsd xmm0, xmm1
add rsp, 8
cvttsd2si rax, xmm0
btc rax, 63
ret
.LC0:
.long 0
.long 1073217536
.LC1:
.long 0
.long 1138753536
*/
концепты-хуепты
−1
А давайте ругать Фрейда
https://imgur.com/a/hH4QLKd
https://imgur.com/a/07wciaX
0
[...]
After some configuration changes, I was able to add the 2000 ports by defining them out manually.
[...]
https://stackoverflow.com/questions/37992007/creating-ftp-service−3
{$APPTYPE CONSOLE}
Procedure G(p: pointer);
Const
Messages: array[false..true] of string = ('Не гниль', 'Гниль');
Begin
Writeln(Messages[p=nil])
End;
Begin
G(nil)
End.
https://ideone.com/XWhPQf
0
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
string rec(const string str, char c){return str;} //syntax error : missing ';' before identifier 'rec', ')' before 'const', ')', ';' before '{',
//'str' : undeclared identifier, 'rec': identifier not found
void cer(){} //'cer' : local function definitions are illegal
main(){ //'main': identifier not found
string s, d="Math.cos",a; //missing '}' before identifier 's', ';' before identifier 's', 's', 'd', 'a' : undeclared identifier
ifstream fin;
vector<string> mas; // 'std::vector' : 'string' is not a valid template type argument for parameter '_Ty', 'mas' : unknown size
//'std::vector' : no appropriate default constructor available
fin.open(mDocWrite); //'void std::basic_ifstream<char,std::char_traits<char>>::open(const char *,std::ios_base::open_mode)' :
//cannot convert argument 1 from 'nsAutoPtr<nsHtml5Tokenizer>' to 'const wchar_t *'
//No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
//if (fin.is_open()) cout<<"1";else cout<<"0";
while(fin>>s) //'s' : undeclared identifier, fatal error C1903: unable to recover from previous error(s); stopping compilation
{bool f=0;
for(int i=0; i<s.size(); ++i)
if (s[i]==d[0])
{
f=1;
for (int j=0; j<s.size()&&j<d.size(); ++j)
if (d[j]!=s[i+j]) f=0;
if (f)
{
a.clear();
for (int j=0; j<i; ++j)
a=a+s[j];
a=a+"0.5*";
for (int j=i; j<s.size(); ++j)
a=a+s[j];
}
}
if (f) {mas.push_back("\n");mas.push_back(a);mas.push_back("\n");}
else mas.push_back(s);
s=rec(s,'0');
}
ofstream fout;
fout.open(mDocWrite);
for (int i=0; i<mas.size(); ++i) fout<<mas[i]<<"\t";
}
предполагалось, что код будет уменьшать cos угла в два раза, но при компиляции выдает ошибки, логику большинства которых не могу понять. Ошибки указал в коде. Подскажите, что не так.
+1
#include <iostream>
#include <type_traits>
#include <utility>
#include <array>
template<size_t Size, typename T, typename FunctorType, size_t... idx>
constexpr std::array<decltype(std::declval<FunctorType>().operator()(std::declval<T>())), Size>
map_impl(const std::array<T, Size> & arr, FunctorType && f, std::index_sequence<idx...>)
{
return std::array{ f(std::get<idx>(arr))... };
}
template<size_t Size, typename T, typename FunctorType>
constexpr std::array<decltype(std::declval<FunctorType>().operator()(std::declval<T>())), Size>
map(const std::array<T, Size> & arr, FunctorType && f)
{
return map_impl(arr, f, std::make_index_sequence<Size>{});
}
struct MyFunctor {
constexpr float operator()(int arg)
{
return static_cast<float>(arg * arg) / 2.0f;
}
};
int main()
{
constexpr std::array arr{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
auto arrMappedFunctor = map(arr, MyFunctor{});
auto arrMappedLambda = map(arr, [](int x) constexpr { return static_cast<float>(x * x) / 2.0f; });
for (auto && x : arrMappedFunctor) {
std::cout << x << ' ';
}
std::cout << std::endl;
for (auto && x : arrMappedLambda ) {
std::cout << x << ' ';
}
std::cout << std::endl;
return 0;
}
0.5 2 4.5 8 12.5 18 24.5 32 40.5 50
0.5 2 4.5 8 12.5 18 24.5 32 40.5 50
Метушня выходит на новый уровень: полноценный map в compile-time. Поддерживает как ручные функторы с перегруженным operator(), так и constexpr-лямбды. При помощи небольшой модификации возможно реализовать поддержку кортежей с произвольными типами.
0
// AFJSONRPCClient.m
//
// Created by [email protected]
// Copyright (c) 2013 JustCommunication
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "AFHTTPRequestOperationManager.h"
/**
AFJSONRPCClient objects communicate with web services using the JSON-RPC 2.0 protocol.
@see http://www.jsonrpc.org/specification
*/
@interface AFJSONRPCClient : AFHTTPRequestOperationManager
/**
The endpoint URL for the webservice.
*/
@property (readonly, nonatomic, strong) NSURL *endpointURL;
/**
Creates and initializes a JSON-RPC client with the specified endpoint.
@param URL The endpoint URL.
@return An initialized JSON-RPC client.
*/
+ (instancetype)clientWithEndpointURL:(NSURL *)URL;
/**
Initializes a JSON-RPC client with the specified endpoint.
@param URL The endpoint URL.
@return An initialized JSON-RPC client.
*/
- (id)initWithEndpointURL:(NSURL *)URL;
/**
Creates a request with the specified HTTP method, parameters, and request ID.
@param method The HTTP method. Must not be `nil`.
@param parameters The parameters to encode into the request. Must be either an `NSDictionary` or `NSArray`.
@param requestId The ID of the request.
@return A JSON-RPC-encoded request.
*/
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
parameters:(id)parameters
requestId:(id)requestId;
/**
Creates a request with the specified method, and enqueues a request operation for it.
@param method The HTTP method. Must not be `nil`.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
*/
- (void)invokeMethod:(NSString *)method
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates a request with the specified method and parameters, and enqueues a request operation for it.
@param method The HTTP method. Must not be `nil`.
@param parameters The parameters to encode into the request. Must be either an `NSDictionary` or `NSArray`.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
*/
- (void)invokeMethod:(NSString *)method
withParameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
/**
Creates a request with the specified method and parameters, and enqueues a request operation for it.
@param method The HTTP method. Must not be `nil`.
@param parameters The parameters to encode into the request. Must be either an `NSDictionary` or `NSArray`.
@param requestId The ID of the request.
@param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the request operation, and the response object created by the client response serializer.
@param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a two arguments: the request operation and the error describing the network or parsing error that occurred.
*/
- (void)invokeMethod:(NSString *)method
0
Ну как вы тут, потомки? Борманд еще живой?