Functions taking NTuple as arguments but imposing (static) size constraints, how to define them? - static

I want to define functions taking NTuples as arguments but with with size constraints.
The idea would be to declare something like:
foo(x::NTuple{K-1,Int},y::NTuple{K,Int}) where {K} = "ok"
However this is not a correct Julia code.
My question is: how to define such kind of functions in Julia?
(For illustration purpose only): for C++ coders, my question is equivalent to "how to translate this kind of C++ code
template <size_t N>
foo(const std::array<int, N-1>& x, const std::array<int, N>& y)
{ ... }
into well formed Julia code."

In this specific case you can do:
foo(x::NTuple{M,Int},y::Tuple{Int, Vararg{Int,M}}) where {M} = "ok"
as the difference in dimensions is fixed.
In a more general case the only thing I know of is to add a condition inside the function:
foo(x::NTuple{M,Int},y::NTuple{K,Int}) where {M,K} =
M + 1 == K ? "ok" : throw(ArgumentError("dimension mismatch"))
and the conditional check should be optimized out by the compiler (at least in this case it seems to be optimized under Julia 1.0.3).

Related

concatenate macros in c in a loop

i want to concatenate a lot of macros in order to pass them as parameter in a struck array. to be more specific i have this struct
static struct
{
unsigned int num_irqs;
volatile __int_handler *_int_line_handler_table;
}_int_handler_table[INTR_GROUPS];
and I want to pass as num_irqs parameter a series of macros
AVR32_INTC_NUM_IRQS_PER_GRP1
AVR32_INTC_NUM_IRQS_PER_GRP2
...
first I thought to use this code
for (int i=0;i<INTR_GROUPS;i++)
{
_int_handler_table[i].num_irqs = TPASTE2(AVR32_INTC_NUM_IRQS_PER_GRP,i);
}
but it takes the i as char and not the specific value each time. I saw also that there is a MREPEAT macro defined in the preprocessor.h but I do not understand how it is used from the examples.
Can anyone can explain the use of MREPEAT or another way to do the above.
Keep in mind the preprocessor (which manipulates macros) runs before the compiler. It's meant to manipulate the final source code to be submitted to the compiler.
Hence, it has no idea of what value has a variable. For the preprocessor, i means i.
What you try to do is a bit complex, especially keeping in mind that preprocessor cannot generate preprocessor directives.
But it can generate constants.
Speaking of which, for your use case, I would prefer to use a table of constants, such as :
const int AVR32_INTC_NUM_IRQS_PER_GRP[] = { 1, 2, 3, 4, 5 };
for (int i=0;i<INTR_GROUPS;i++)
{
_int_handler_table[i].num_irqs = TPASTE2(AVR32_INTC_NUM_IRQS_PER_GRP[i]);
}
C doesn't work like that.
Macros are just text-replacement which happens att compile-time. You can't write code to construct a macro name, that doesn't make sense. The compiler is no longer around when your code runs.
You probably should just do it manually, unless the amount of code is very large (in which case code-generation is a common solution).

Can a two-dimensional array in C be initialized without explicit size?

I have a question regarding two-dimensional arrays in C. I know now (from direct compiler experience) that I can't initialize such an array analogously to one-dimensional arrays like this:
int multi_array[][] = {
{1,2,3,4,5},
{10,20,30,40,50},
{100,200,300,400,500}
};
> compiler output:
gcc -o arrays arrays.c
arrays.c: In function ‘main’:
arrays.c:8:9: error: array type has incomplete element type
The closest solution that works is to provide the number of columns explicitly like this:
int multi_array[][5] = {
{1,2,3,4,5},
{10,20,30,40,50},
{100,200,300,400,500}
};
My question is: can it be done neatly without supplying the number explicitly (which after all the compiler should be able to infer itself)? I'm not talking about manually constructing it with malloc or something but rather something close to what I tried.
Also, can someone knowledgeable about C compilers explain from a low-level perspective why my initial attempt does not work?
I used plain gcc with no non-standard options to compile the code.
Thanks
2D arrays in C are stored in contiguous memory locations. So if you do not provide the number of rows or the number of columns, how will the compiler know how many rows and column there are?
For a row major matrix, rows contents are at contiguous memory positions. So you need to specify at least the number of columns. Similarly for a column major matrix, you need to specify at least the number of rows. Whether it is row major or column major is defined by architecture. It seems that what you have is a row major architecture.
You can do this using the C99 compound literal feature.
A partial idea is that the length of an initializer list can be determined like this:
sizeof (int[]){ 1, 2, 3, 4, 5 } / sizeof(int)
We need a workaround for the fact that the only way you can pass an argument containing a comma to a macro is to put parentheses around (part of) the argument:
#define ROW(...) { __VA_ARGS__ }
Then the following macro deduces the second dimension from the first row:
#define MAGIC_2DARRAY(type, ident, row1, ...) \
type ident[][sizeof (type[])row1 / sizeof (type)] = { \
row1, __VA_ARGS__ \
}
It only works if there are at least two rows.
Example:
MAGIC_2DARRAY(int, arr, ROW(7, 8, 9), ROW(4, 5, 6));
You probably do not want to use this in a real program, but it is possible.
For passing this kind of array to functions, the C99 variable length array feature is useful, with a function like:
void printarr(int rows, int columns, int array[rows][columns]) { ... }
called as:
printarr(sizeof arr / sizeof arr[0], sizeof arr[0] / sizeof arr[0][0], arr);
Not a direct answer to those questions in the original post, I just want to point out that what the asker propose may be not such a good or useful idea.
The compiler indeed can infer from
int multi_array[][] = {
{1,2,3,4,5},
{10,20,30,40,50},
{100,200,300,400,500}
};
the structure of multi_array.
But when you want to declare and define a function (this declaration and definition could be in another compilation unit or source file) that supposes to accept multi_array as one of its argument, you still need to do something like
int foo(..., int multi_array[][COL], ...) { }
Compiler needs this COL to do proper pointer arithmetic in foo().
Usually, we define COL as a macro that will be replaced by an integer in a header file, and use it in the definitions of multi_array and foo():
int multi_array[][COL] = { ... };
int foo(..., int multi_array[][COL], ...) { }
By doing this, it is easy to make sure they are the same. And let compiler to infer the structure of multi_array according to its initialization, when you give it a wrong initialization, you actually introduce a bug in your code.
No you can't do it. If you even don't initialize, you can't define an int array[][];
Create a structure with 1d arrays. However, if you follow this method you can create new arrays but it will be a function call to change sizes and values. A dynamic matrix approach could come close to solving your issue.

Create a min() macro for any type of array

I would like to create a C macro returning the scalar minimum for any type of static array in input. For example:
float A[100];
int B[10][10];
// [...]
float minA = MACRO_MIN(A);
int minB = MACRO_MIN(B);
How can I do so?
It can be probably be done with GCC extensions, but not in standard C. Other compilers might have suitable extensions, too. It will of course make the code fantastically hard to port. I would advise against it, since it's quite hard to achieve it will be "unexpected" and probably act as a source of confusion (or, worse, bugs) down the line.
You're going to have to declare a temporary variable to hold the max/min seen "so far" when iterating over the array, and the type of that variable is hard to formulate without extensions.
Also returning the value of the temporary is hard, but possible with GCC extensions.
To make the above more concrete, here's a sketch of what I imagine. I did not test-compile this, so it's very likely to have errors in it:
#define ARRAY_MAX(a) ({ typeof(a) tmp = a[0];\
for(size_t i = 1; i < sizeof a / sizeof tmp; ++i)\
{\
if(a[i] > tmp)\
tmp = a[i];\
}\
tmp;\
})
The above uses:
({ and }) is the GCC Statement Expressions extension, allowing the macro to have a local variable which is used as the "return value".
typeof is used to compute the proper type.
Note assumption that the array is not of zero size. This should not be a very limiting assumption.
The use of sizeof is of course standard.
As I wrote the above, I realize there might be issues with multi-dimensional arrays that I hadn't realized until trying. I'm not going to polish it further, though. Note that it starts out with "probably".

What is the use of function pointers? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the point of function pointers?
I am trying to understand where in the practical scenarios function pointers are used.
and also can anyone please give me a practical example where we have to pass function itself as an argument to another function.
Function pointers can be useful when you want to create callback mechanism, and need to pass address of a function to another function.
They can also be useful when you want to store an array of functions, to call dynamically for example.
Callback routines appear to be the most common scenario put forth thus far. However, there are many others ...
Finite State Machines where the elements of (multi-dimensional) arrays indicate the routine that processes/handles the next state. This keeps the definition of the FSM in one place (the array).
Enabling features and disabling of features can be done using function pointers. You may have features that you wish to enable or disable that do similar yet distinct things. Instead of populating and cluttering your code with if-else constructs testing variables, you can code it so that it uses a function pointer, and then you can enable/disable features by changing/assigning the function pointer. If you add new variants, you don't have to track down all your if-else or switch cases (and risk missing one); instead you just update your function pointer to enable the new feature, or disable the old one.
Reducing code clutter I touched upon this in the previous example. Examples such as ...
switch (a) {
case 0:
func0();
break;
case 1:
func1();
break;
case 2:
func2();
break;
case 3:
func3();
break;
default:
funcX();
break;
}
Can be simplified to ...
/* This declaration may be off a little, but I am after the essence of the idea */
void (*funcArray)(void)[] = {func0, func1, func2, func3, funcX};
... appropriate bounds checking on 'a' ...
funcArray[a]();
There are many more. Hope this helps.
One common use is to implement a callback function.
Try to sort something by using qsort library function. It's last parameter is a pointer to the comparator function written by you.
The first thing that comes to my mind as a very useful application is a button. Take the following code:
int buttonID = CreateButton ("Click Me!", 100, 100, 200, 100, onClick);
This would create a button at (100,100) with width 200 and height 100. Every time you click it, onClick is called.
I use something similar in a personal Windows API wrapper. It makes creating buttons etc so much easier.
There are two major uses for function pointers:
callbacks - used for event handlers, parser specialization, comparator function passing...
plugins and extensions - the pointers to functions provided by plugins or library extensions are gatherd by a standard functio GetProcAddress, dlsym or similar, which take the function identifier as name and return a function pointer. Absolutely vital for APIs like OpenGL.
Well, the #1 stock answer is: qsort. The comparator routine that qsort will use is passed as a function pointer. A lot of other “generic algorithm” functions will take comparators in similar ways; e.g. perhaps a hashtable implementation might accept your hash function.
C-language GUI toolkits and application frameworks (e.g. Gnome/Gtk+/Glib) often accept function pointers as “callbacks” for timer or user interface events. (EG: “call this function whenever this button is clicked” or “…whenever this timer expires”)
In fact, most “OOP-like” or “event-driven” code in C will accept function pointers for a similar reason.
You can use it to pass a callback to a function. For instance, you might want to sort an array using qsort(). This function takes a comparison function as one of its arguments, which means that you can use your own sorting orders:
// All odd numbers are before even numbers
int cmpoddeven(const void *xp, const void *yp) {
int x = *((int*) xp);
int y = *((int*) yp);
if(x == y)
return 0;
if(x % 2 == y % 2) {
return (x < y ? -1 : 1);
if(x % 2 == 1)
return -1;
return 1;
}
int main() {
int array[] = {1, 2, 3, 4, 5};
// calling qsort with cmpoddeven as the comparison function
qsort(array, 5, sizeof(int), &cmpoddeven);
// array == {1, 3, 5, 2, 4};
}
In MOST cases, it's essentially the C way of doing dependency inversion. The wiki article states:
A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.
The classic example ofqsort does this in the sense that the higher-level sort function does not depend on the type, size, or comparison method of the data to be sorted. So if you qsort() an array of ints, the details are sizeof(int) and your compare implementation. The abstraction is an array of arbitrarily sized elements and a function that compares elements of that type.
See also: Inversion of Control.
I'm surprised no one has mentioned pthread_create() as an example.
The only common use I can think of that cannot be generalized as dependency inversion is implementing switch-like flow control on non-switchable data types. For example, if you've ever wanted to switch on a string, create arrays mapping sorted string keys to function pointers and do a binary search. It's not O(1) like a switch, but better than blindly doing strcmp()'s in a big if-else until you find a match. But maybe not any better than tokenizing the string and using an actual switch.

Reassemble float from bytes inline

I'm working with HiTech PICC32 on the PIC32MX series of microprocessors, but I think this question is general enough for anyone knowledgable in C. (This is almost equivalent to C90, with sizeof(int) = sizeof(long) = sizeof(float) = 4.)
Let's say I read a 4-byte word of data that represents a float. I can quickly convert it to its actual float value with:
#define FLOAT_FROM_WORD(WORD_VALUE) (*((float*) &(WORD_VALUE)))
But this only works for lvalues. I can't, for example, use this on a function return value like:
FLOAT_FROM_WORD(eeprom_read_word(addr));
Is there a short and sweet way to do this inline, i.e. without a function call or temp variable? To be honest, there's no HUGE reason for me to avoid a function call or extra var, but it's bugging me. There must be a way I'm missing.
Added: I didn't realise that WORD was actually a common typedef. I've changed the name of the macro argument to avoid confusion.
You can run the trick the other way for return values
float fl;
*(int*)&fl = eeprom_read_word(addr);
or
#define WORD_TO_FLOAT(f) (*(int*)&(f))
WORD_TO_FLOAT(fl) = eeprom_read_word(addr);
or as R Samuel Klatchko suggests
#define ASTYPE(type, val) (*(type*)&(val))
ASTYPE(WORD,fl) = eeprom_read_word(addr);
If this were GCC, you could do this:
#define atob(original, newtype) \
(((union { typeof(original) i; newtype j })(original)).k)
Wow. Hideous. But the usage is nice:
int i = 0xdeadbeef;
float f = atob(i, float);
I bet your compiler doesn't support either the typeof operator nor the union casting that GCC does, since neither are standard behavior, but in the off-chance that your compiler can do union casting, that is your answer. Modified not to use typeof:
#define atob(original, origtype newtype) \
(((union { origtype i; newtype j })(original)).k)
int i = 0xdeadbeef;
float f = atob(i, int, float);
Of course, this ignores the issue of what happens when you use two types of different sizes, but is closer to "what you want," i.e. a simple macro filter that returns a value, instead of taking an extra parameter. The extra parameters this version takes are just for generality.
If your compiler doesn't support union casting, which is a neat but non-portable trick, then there is no way to do this the "way you want it," and the other answers have already got it.
you can take the address of a temporary value if you use a const reference:
FLOAT_FROM_WORD(w) (*(float*)&(const WORD &)(w))
but that won't work in c :(
(c doesn't have references right? works in visual c++)
as others have said, be it an inlined function or a temp in a define, the compiler will optimize it out.
Not really an answer, more a suggestion. Your FLOAT_FROM_WORD macro will be more natural to use and more flexible if it doesn't have a ; at the end
#define FLOAT_FROM_WORD(w) (*(float*)&(w))
fl = FLOAT_FROM_WORD(wd);
It may not be possible in your exact situation, but upgrading to a C99 compiler would solve your problem too.
C99 has inline functions which, while acting like normal functions in parameters and return values, get improved efficiency in exactly this case with none of the drawbacks of macros.

Resources