Search code examples
clinuxrepresentation

Modifying the representation of for loop in C


I have a the given for loop written multiple times and it is annoying to type that everytime.

Note that they are in they are in different functions.so, code optimization isn't the problem here. but instead representation

for(int j=0; j<PS; j++){
   for (int k=0; k<CLS;k++){

Would it be possible to represent it with the help of a pragma or something.. so, that I can use it in the following fashion..

#pragma mycurrentlooping
{
  blah[j][k]...
}

Would this be possible? if yes, how? or what is the best possible way to do this.

Would doing this effect the performance?

This may sound stupid..but i really have many such individual functions that do different operations.


Solution

  • You can use #define to define a MACRO for that, like this:

    #define loop_till(x) for(int j=0; j<(x); j++)

    You do it at the top of your source file, then use it as:

    loop_till(PS)
    {
         loop_till(CLS)
         {
          ...
         }
    }
    

    To read more about (function like) pre-processor macros, read this