GP32 #define Command


ConsoleTom

Member
Joined
Dec 4, 2003
Messages
106
Age
48
Location
Germany
Website
Visit site
Hi !

How are #define commands handled ? Is it just like copying a text ?

example:

#define INT_X 1+2+3+4

when i have this line:

for (i=0;i<=INT_X;i++) { ... }

would the compiler work like:
1.) for (i=0;i<=1+2+3+4;i++) { ... } or
2.) for (i=0;i<=7;i++) { ... }

My real question: For defining bits. Which one is better:

#define A 1<<0 // bit 0
#define A 1<<1 // bit 1
#define A 1<<2 // bit 2

or

#define A 1 // bit 0
#define A 2 // bit 1
#define A 4 // bit 2

Or how do good programmers write such code ?

Perhaps its stupid, but i want to write code that is as fast as possible.

Greetings

Tobias

SDK: DevkitARM_R8
 
#define is for constants

For variables you need to use "int x;" (where x is the variable name) you can use "
int x,y;" to make multiple variables at a time.

Oh, and I'm not a good teacher. But Thinking in C++ volumes 1 & 2 are good C and C++ books and are free. Get them at mindview.net.
 
see this:

http://www.newtonlabs.com/ic/ic_9.html

the #define preprocessor command can be used for simple substitution

i.e

#define INT_X 1+2+3+4


for (i=0;i<=INT_X;i++) { ... }

// would be replaced with:

for (i=0;i<=1+2+3+4;i++)


this substitution occurs before any code is compiled.

its a good idea to use braces '(' ')' in define so that there wont be any prescedence problems when you use it in your code.

i.e #define INT_X (1+2+3+4)

you can also use #define for more complex macros, see the link.

umm, i'd take a guess that:

#define A 1 // bit 0
#define A 2 // bit 1
#define A 4 // bit 2

would be better because otherwise 1<<1 etc would need to be evaluated everytime it is used in your code, but i think bit shifting is relatively fast anyway.
 
When I define bit constants I always use hexadecimal notation as it is more readable.

Ex.:

Code:
#define A 0x01  // Bit 1
#define B 0x02  // Bit 2
#define C 0x04  // Bit 3
#define D 0x08  // Bit 4
#define E 0x10  // Bit 5
#define F 0x20  // Bit 6
#define G 0x40  // Bit 7
#define H 0x80  // Bit 8

Oankali
 
When using bit constants, I normally use enums, but otherwise I use #define's.

enum
{
A = 0x01,
B = 0x02,
C = 0x04,
[...]
} VDC_CR_Bits;

One important thing to note : Treat #define's only as simple substitution. Secondly, Nearly all C compilers are single pass, so don't try to use this text replacement ability in #define statements themselves - it could result in some interesting side effects (bugs, or weird compiler errors) which could be real nasty to find.
 
Back
Top