#define PUMP [0,1]
when I call a function like this:
for (index = 0;index < 8; index++)
{
get_motor_current(PUMP[index]);
}
The intent is to do get_motor_current([0][index]) and get_motor_current([1][index])
Thank you very much.
You can do it by having the macro expand into a compound literal.
#include <stdio.h>
#define PUMP ((const int[]){0, 1})
int main(void) {
for (int index = 0;index < 2; index++)
{
printf("%d\n", PUMP[index]);
}
}
Long story short, you can't do what you're trying to do the way you're trying to do it. All the C preprocessor does is perform direct text substitutions. So, after preprocessing, your code snippet would look like:
for (index = 0;index < 8; index++)
{
get_motor_current([0,1][index]);
}
which is not valid C.
Also, square brackets [] are only used for indexing an existing array. If you want to initialize an array with a list of values, you write a list of values enclosed in curly braces {} like so:
int some_array[] = {1, 2, 3, 4};
You don't need to define an array size here (i.e. say some_array[4]) because the compiler just counts the number of items in the list and does that for you.
Related
Shake sort of vector:
program works, but:
I was trying to use the same function for bubble up and bubble down for shake sort (bubble up to get the MAX value to the right and bubble down to get the min value to the left). In order to do it I was trying to use the following MACRO which does not compile:
sign is '+' and oper is '>' for bubble
sign is '-' and oper is '<' for bubble down
for bubble up -
start is iterator i (iterated the Vector indices)
end is n-1-i;
for bubble down -
swap start and end values
#define bubble_up_down(var_t, pVector, _Is_swp, start, end, sign, oper)\
{\
var_t current_index;\
var_t current_val;\
var_t next_val;\
for (current_index = *(start) ; current_index (oper) *(end) ; (sign)(sign)current_index){\
{\
VectorGet((pVector), current_index, ¤t_val);\
VectorGet((pVector), current_index(sign)1, &next_val);\
if(current_val (oper) next_val)\
{\
VectorSet((pVector), current_index, next_val);\
VectorSet((pVector), current_index(sign)1, current_val);\
*(_Is_swp) = 1;\
}\
}\
}
Need your advice to fix this macro.
It is not really clear why you want to use a macro here. Do you want to avoid duplicaing code? Or do you want to make your sorting routine type independent?
Anyway, your macro has several errors:
You've probably read that you should guard macro arguments with parentheses. That is usually good advice, because macros are text replacements; for example infamous SQ(x + 1) will resolve to x + 1*x + 1. In your case, the advice is wrong-headed. You will get syntactically wrong "operators" such as (-) and (<) in your code. Just use sign and oper.
Even so, sign sign will resolve to - - or + +, which is not what you want. You could rewrite i++ to the equally valid i = i + 1 or you could use the token-pasting operator, sign##sign, which would produce -- or ++.
Macros aren't functions. You are probably going to invoke your macro inside a function. All local variables that are in scope hen you invoke the macro are also in scope for the macro. That means there is probably no need to define all these pointers.
Why do you pass the array element type, var_t? I reckon that SetVector and GetVector aren't macros, so the type independence falls flat.
If var_t is the type of your array elements, your index isn't necessarily of the same type; it should be an integer type. (Your elements must be comparable with the < operator, so it is one of the arithmetic types, but image what happens if you have an array of char that is longer than 256 elements?)
If your elements are of arithmetic type, there's probably no need for the GetValue and SetValue calls. You can just assign values with the = operator .
All this makes me think that you don't really know what you're doing. That plus the known pitfalls and shortcomings of macros are a good reason not to use any macros here.
Addendum In comments, The PO has said that the macro should achieve two things: It should avoid repeated code and it should make the sorting independent of the types of the array elements. These are two different things.
Writing short local macros to avoid repeating code can be a useful technique, especially, if the code needs to keep variables in sync in several places. Is it useful in your situation?
So you've got your upward-bubbling code:
int done = 0;
while (!done) {
done = 1;
for (int i = 1; i < n; i++) {
if (a[i - 1] > a[i]) {
swap(a, i - 1, i);
done = 0;
}
}
}
(This uses a swap function to swap two array elements. It is more straightforward than your version, because it doesn't use get/set accessor functions.) Now you write the downward-bubbling counterpart:
while (!done) {
done = 1;
for (int i = n - 1; i > 0; i--) {
if (a[i - 1] > a[i]) {
swap(a, i - 1, i);
done = 0;
}
}
}
These two snippets differ only in the loop control. Both visit all indices from 1 to n - 1. So your macro needs to pass the start and end values. But it also needs to know which way the comparison goes – less than or greater than – and whether to increment or to decrement the index. That's four pieces of data for a simple loop.
You could try to get rid of the comparison and use != for both directions. But then your loops will fail if the array is empty.
The above backwards loop will already fail on empty arrays when you use an unsigned integer as index. Forward and backward lops are asymmetric an C, because the lower and upper bounds are asymmetric, too: Lower bound are always inclusive, upper bound are always exclusive. This forward loop:
for (unsigned int i = 0; i < n; i++) ...
Has the following backward equivalent:
for (unsigned int i = n; i-- > 0; ) ...
Here, the decrement occurs in the condition and the update part is empty. The advantage is that it uses exactly the same bounds, 0 and n, verbatim, but by decrementing before entering the loop body, the same valid range of numbers, 0 to n - 1 are visited. And it works with unsigned ints, which are a natural choice for looping variables.
To cut a long story short: Forward and backward loops are asymmetric in C, so it is not easy to write a macro for them. C's for syntax is more verbose than for i = 1 to n, but that's how it is. Embrace it and alleviate the typing pain by chosing appropriate index names: it's i, not current_index.
Can you make the code less redundant without macros? Of course: You can write two functions for bubbling up and down once:
static int bubble_up(int a[], int n)
{
int done = 1;
for (int i = 1; i < n; i++) {
if (a[i - 1] > a[i]) {
swap(a, i - 1, i);
done = 0;
}
}
return done;
}
static int bubble_down(int a[], int n)
{
int done = 1;
for (int i = n; i-- > 1; ) {
if (a[i - 1] > a[i]) {
swap(a, i - 1, i);
done = 0;
}
}
return done;
}
(These functions are static, i.e. private to the current compilation unit.) Now your actual sorting functions look like this:
void sort_bubble_up(int a[], int n)
{
int done = 0;
while (!done) {
done = bubble_down(a, n);
}
}
void sort_bubble_down(int a[], int n)
{
int done = 0;
while (!done) {
done = bubble_down(a, n);
}
}
void sort_shaker(int a[], int n)
{
int done = 0;
while (!done) {
done = bubble_up(a, n) || bubble_down(a, n);
}
}
If you are not afraid of empty loop bodies, you can even get them down to:
void sort_bubble_up(int a[], int n)
{
while (bubble_down(a, n)) { }
}
void sort_bubble_down(int a[], int n)
{
while (bubble_down(a, n)) { }
}
void sort_shaker(int a[], int n)
{
while (bubble_up(a, n) || bubble_down(a, n)) { }
}
All this code works only for int arrays, though. The standard library's way of approaching type independence is to work on the byte level via void * pointers and user-defined comparison functions. The sorting function qsort does this, for example.
C++ and other languages have templates, where you can write an algorithm for several types. When you "instantiate" a template, the compiler creates a function for just this type, which is then called.
You could emulate this with macros. If you just want to call your macro in the function body, you could define:
#define BUBBLE_SORT(ARRAY, N, TYPE) do { \
int done = 0; \
int i; \
\
while (!done) { \
done = 1; \
\
for (i = 1; i < N; i++) { \
if (ARRAY[i - 1] > ARRAY[i]) { \
TYPE sawp = ARRAY[i]; \
\
ARRAY[i] = ARRAY[i - 1]; \
ARRAY[i - 1] = swap; \
done = 0; \
} \
} \
} \
} while (0)
and then use the macro like so:
char c[] = "Mississippi";
BUBBLE_SORT(c, strlen(c), char);
(That do { ... } while (0) thing around thze macro makes the macro behave like a function call, sort of. The new scope of the loop body allows for local variables.)
The problem here is that such multi-line macros are hard to debug. When there is an error in the body, you just get the number of the line where the macro is invoked in an error message. (But you can use -E with most compilers to see how the preprocessor resolves that macro.)
Conclusion:
Macros can be useful, but you have to know what you are doing. In general, try to avoid them, because they are hard to debug and often hard to understand for others. (And this other person might be you half a year later.)
If you must use macros, try to make then look as natural as possible. Passing operators like > or + should make you wary.
Use functions, not macros, for common code.
Embrace C's way to deal with different types. It will be more useful (if less fun) to learn how qsort works than to fiddle with macros for a bubble sort implementation.
If you really need to write a lot of type-independent code, you probably shouldn't use C.
This my code as it stands:
int sliderNum; // Variable Declaration //
// Loop Sequencer //
for (sliderNum = 41; sliderNum <= 48; sliderNum = sliderNum + 1)
However I need to change this so the loop no longer counts from 41-48 but instead counts e.g 73,71,34,46,52,4,17 etc. So a specific set of numbers one after another but not like counting normally.....hope that makes sense.
As you can probably tell, I'm pretty new to this programming stuff so any help would be greatly appreciated.
Cheers.
int a[] = {1,4,7,10};
for(int i=0; i<sizeof(a)/sizeof(a[0]); ++i)
{
....process a[i]
}
I recommend consulting a good book on c.
Regarding the code: This is basically looping over an array with iterations = size in bytes of the array / size in bytes of an element of array
You might even place the array literally within the for loop definion. This way, it somewhat resembles "with" statement, that is common in Python:
#define ARRAY_LEN(a) (sizeof(a)/sizeof(*a))
int main()
{
for (int a[] = {73, 71, 34, 46, 52, 4, 17}, i = 0; i < ARRAY_LEN(a); i++) {
// ...
}
}
Personally, I wouldn't write such code on production, as it may be questioned as "too clever", whereas putting the array at the top of loop seems to make it more readable.
I am trying to define a constant that would have the following in it
ch[co].gold < 10000*100
how can I make it, something like
define x = ch[co].gold < 10000*100;
so that every time I write
if (x) {say(cn,"You need 10 000 gold coins");}
Or that is not possible?
Function:
int x(int val) {
return (val < 10000 * 100);
}
Usage
// ...
if (x(ch[co].gold)) {
printf("You need 10 000 gold coins.\n");
}
// ...
Well, here is my solution
struct s {
int gold;
};
const int co = 2;
struct s ch[] = {112,2321,3234};
#define x() ch[co].gold < 10000*100
int main(){
if (x()) {
}
return 0;
}
Is this what you are expecting?
#define x (ch[co].gold < 10000*100)
Add this line of code before the place you use it, usually it's just below the #includes.
Conventionally, we use capital letters with clearer meanings instead of x.
#define is simply text substition performed by the preprocessor.
To do what you say you want use the following #define:
#define x ch[co].gold < 10000*100
Every time the preprocessor encounters the symbol x it will replace it with ch[co].gold < 10000*100.
I think that what you really want is to make it a proper function as suggested by pmg. It is a wiser choice.
Here I know that the following code simply copies the character i rather than its value to the preprocessor statement (which makes a error for undefined symbol i in compile-time).
What I want is:
Is their a way such that the compiler treats, i as a variable with some value rather than a character ?
#include <stdio.h>
#define PRINT(x) printf("%d \n", y ## x)
int main(void) {
int y1=0 , y2=1 , y3=4;
for(int i=1; i <= 3; ++i) {
PRINT(i);
}
return 1;
}
About the pre-processor
First of all, I think there's a need to clarify how the preprocessor works: it pre-processes the input files, which means it runs before the compiler. Unfortunatly, for historical reasons, it doesn't know anything about C or C++, doesn't parse anything, and just does very simple textual operations on words and parenthesis. Just to illustrate my point:
#define this __FILE__
#define file -- Hell no!
#define fine(a, b) fine: a ## _ ## b
Ok, so this is not a valid C or C++ file
But the preprocessor will run just fine(go, try!)
Run this with a pre-processor, for example gcc -x c -E -P test.txt and you'll get:
Ok, so "test.txt" is not a valid C or C++ -- Hell no!
But the preprocessor will run just fine: go_try!
So, obviously, when the preprocessor sees PRINT(i) in your code, it replaces it with printf("%d \n", yi) without thinking much about it. And it has absolutely no idea i is a variable, don't even think about evaluating it's value.
Solutions
Basically, what you want is print a bunch of numbers.
You could simply do
printf("0\n1\n4\n");
But this lacks makes changing numbers cumbersome,
so let's go with
printf("%d\n%d\n%d\n", 0, 1, 4);
Which makes it easy to change a number, but not to add/remove one.
Ok so how about:
printf("%d\n", 0);
printf("%d\n", 1);
printf("%d\n", 4);
Yeah, you can change/add/remove numbers easily but as any sane programmer you hate repetition. So, we need some kind of loop.
By far the simplest and most straightforward way to iterate in C is at runtime, using an array:
int [] y = { 0, 1, 4 };
for(int i = 0; i < sizeof(y)/sizeof(int); ++i) {
printf("%d\n", y[i]);
}
If you want, you can hide the printf using a function:
inline void print_int(int* y, int i) { print_int(y[i]); }
int [] y = { 0, 1, 4 };
for(int i = 0; i < sizeof(y)/4; ++i) print_int(y, i);
And going further with functions:
inline void print_int(int x) { printf("%d\n", x); }
inline void print_int(int* y, int i) { print_int(y[i]); }
inline void print_ints(int * y, int n)
{
for(int i = 0; i < n; ++i)
print_int(y, i);
}
template<int n> // C++
inline void print_ints(const int[n] & y) { print_ints(&y[0], n); }
int [] y = { 0, 1, 4 };
print_ints(y); // C++
// or in C:
print_ints(y, sizeof(y)/sizeof(int));
Now, what if you absolutely want the generated code to look like solution 3. ? This means you need the iteration to happen at compile-time. Tricky!
That's where the preprocessor can come into play. There are (hacky) ways to make it do this kind of things. I strongly recommend not implementing this yourself (except to play), but use the Boost.preprocessor library instead:
#define PRINTER(R,D, NUMBER) printf("%d\n", NUMBER);
#define NUMBERS (0, 1, 4)
BOOST_PP_LIST_FOR_EACH(PRINTER, _, BOOST_PP_TUPLE_TO_LIST(NUMBERS))
// will expand to printf("%d\n", 0); printf("%d\n", 1); printf("%d\n", 4);
Under standard C, this is not possible; during preprocessing, the compiler simply sees the identifier i as simply that - an identifier. It does not know that i is of type int, or that it's even a variable in the first place.
The easiest way to achieve what's intended is to use an array, like so:
int i;
int y[] = { 0, 1, 4 };
for (i = 0; i < 3; i++) // NOTE: arrays in C start at index 0, not 1
{
printf("%d \n", y[i]);
}
Also note that I got rid of the macro, as you want to use the value of a runtime variable i to select another runtime variable.
Consider:
enum Test
{
a = 3,
b = 7,
c = 1
};
I want to access the enum using an index. Something like this:
for (i=0; i<n; i++)
doSomething((Test)i);
How can I do something like this, where I will be able to access the enum using an index, though the members of the enum have different values?
This is the best you can do:
enum Test { a = 3, b = 7, c = 1, LAST = -1 };
static const enum Test Test_map[] = { a, b, c, LAST };
for (int i = 0; Test_map[i] != LAST; i++)
doSomething(Test_map[i]);
You have to maintain the mapping yourself.
You can't do that. A C enum is not much more than a bunch of constants. There's no type-safety or reflection that you might get in a C# or Java enum.
Your question demonstrates you don't really understand what an enum is for.
It is not something that can be indexed, nor is there ever any reason to. What you have defined is actually just 3 constants named a, b, and c, whose values are 3, 7, and 1 respectively.
As someone else mentioned, this is not the purpose of an enum. In order to do what you are asking, you can simply use an array:
#define a 3
#define b 7
#define c 1
int array[3] = { a, b, c };
int i;
for( i = 0; i < sizeof(array)/sizeof(array[0]); i++ ) {
doSomething( array[i] );
}