954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

for loop as a macros

could somebody tell wats wrong with this
#define FOR(x,n)for(typeof(x);x

aryansmit3754
Newbie Poster
4 posts since Jan 2009
Reputation Points: 9
Solved Threads: 0
 

Just don't use macros for loops.

MosaicFuneral
Posting Virtuoso
1,691 posts since Nov 2008
Reputation Points: 888
Solved Threads: 116
 

Firstly, there is no space between the closing bracket at the end of FOR(x,n) and preceding the rest. That's a stylistic concern, but badly hurts readability.

Second, and more significantly, typeof() is not a standard function or operator in C++. It is an extension specific to g++ (GNU c++) in which typeof(x) expands to be type of x and will trigger a compiler error with every compiler that does not support that extension. Within a for loop (assuming you're using g++), if x is an int, then FOR(x,n) would expand to for (int; x < n; x++) which is invalid code.

grumpier
Posting Whiz in Training
211 posts since Aug 2008
Reputation Points: 193
Solved Threads: 32
 

Apart from anything else this useless macros must be

#define FOR(x,n)for(typeof(x)x=0;x<(n);x++)
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

"#define FOR(x,n)for(typeof(x)x=0;x<(n);x++)" won't even work. In order for typeof() to function, x has to already exist, and if x already exists the compiler will complain that you're redeclaring x. EG:

int x;

FOR(x,10)
   cout<<"Looping"<<endl;

will expand to "for(int x=0; x<(10);x++", but you already declared x... The closest you might want is "FOR(n) for(int x=0; x<(n); x++)" but I fail to see much point. If you're going to macro a for loop, do so because you're controlling the entire loop for a specific set. Such as:

#define ITERATE_DEVICE_LIST    for(int i=0; i < NUM_DEVICES; i++)

At least this ensures that indexing errors need only be fixed in the macro and prevents stray typos from causing problems in the future.

bobpaul
Newbie Poster
1 post since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

Why would anyone do this? Ouch my eyes. Use either std::for_each, BOOST_FOR_EACH,
or even manually.

firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You