Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Special Interest Groups
  3. C++ Gurus
  4. Simplest way to for loop
Forum Updated to NodeBB v4.3 + New Features

Simplest way to for loop

Scheduled Pinned Locked Moved Unsolved C++ Gurus
42 Posts 10 Posters 10.0k Views 7 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Q Offline
    Q Offline
    Q139
    wrote on last edited by
    #1

    What is easyest way to loop range based?
    for example i am tired of typing out for(int a=0; a<b; a++);
    Also cannot use for(auto a:b) as it wont provide index at;
    Is it possible to dofor(int a=0:5) to loop 0-5 or something simple like this?

    jsulmJ 1 Reply Last reply
    0
    • Q Q139

      What is easyest way to loop range based?
      for example i am tired of typing out for(int a=0; a<b; a++);
      Also cannot use for(auto a:b) as it wont provide index at;
      Is it possible to dofor(int a=0:5) to loop 0-5 or something simple like this?

      jsulmJ Offline
      jsulmJ Offline
      jsulm
      Lifetime Qt Champion
      wrote on last edited by
      #2

      @Q139

      for (int a : {0, 1, 2, 3, 4, 5}) {}
      

      https://forum.qt.io/topic/113070/qt-code-of-conduct

      Q 1 Reply Last reply
      2
      • Q Offline
        Q Offline
        Q139
        wrote on last edited by Q139
        #3

        Is this very bad practice?

        #define afor(min,max) for(int i=min; i<max; i++)
        #define afor(max) for(int i=0; i<max; i++)
        
        afor(3)
            infoLine(n(c[i]));
        
        JonBJ 1 Reply Last reply
        0
        • Q Q139

          Is this very bad practice?

          #define afor(min,max) for(int i=min; i<max; i++)
          #define afor(max) for(int i=0; i<max; i++)
          
          afor(3)
              infoLine(n(c[i]));
          
          JonBJ Offline
          JonBJ Offline
          JonB
          wrote on last edited by JonB
          #4

          @Q139
          Which bit of it? :) [I'll ignore the n(c[i]); I'll ignore the missing parentheses when you use the parameters.] I wouldn't replace a for loop with a macro. I wouldn't define two macros which depend on how many arguments you pass them. Typing your for(int a=0; a<b; a++) really doesn't seem like the end of the world to me, if that's the worst thing you have to worry about in C++ ... :)

          Quite why @jsulm gave you the suggestion he did I'm not sure, it's hardly a pattern to follow.

          1 Reply Last reply
          0
          • jsulmJ jsulm

            @Q139

            for (int a : {0, 1, 2, 3, 4, 5}) {}
            
            Q Offline
            Q Offline
            Q139
            wrote on last edited by Q139
            #5

            @jsulm said in Simplest way to for loop:

            for (int a : {0, 1, 2, 3, 4, 5}) {}

            How can i make a text macro to go for (int a : {0, 1, 2, 3, 4, 5......1000000}) {}?

            Chris KawaC 1 Reply Last reply
            0
            • Q Q139

              @jsulm said in Simplest way to for loop:

              for (int a : {0, 1, 2, 3, 4, 5}) {}

              How can i make a text macro to go for (int a : {0, 1, 2, 3, 4, 5......1000000}) {}?

              Chris KawaC Offline
              Chris KawaC Offline
              Chris Kawa
              Lifetime Qt Champion
              wrote on last edited by
              #6

              @Q139 said:

              How can i make a text macro to go for (int a : {0, 1, 2, 3, 4, 5......1000000}) {}?

              You could use std::iota :) Just joking. Don't do it, it's a bad idea to create a static range of consecutive numbers just to iterate over it. It's a waste of cycles and memory. There's nothing wrong with for(int a=0; a<b; a++);. Don't go into macros. They'll save you few keystrokes and then add 100x that if you ever need to debug that loop.

              Q 1 Reply Last reply
              3
              • Chris KawaC Chris Kawa

                @Q139 said:

                How can i make a text macro to go for (int a : {0, 1, 2, 3, 4, 5......1000000}) {}?

                You could use std::iota :) Just joking. Don't do it, it's a bad idea to create a static range of consecutive numbers just to iterate over it. It's a waste of cycles and memory. There's nothing wrong with for(int a=0; a<b; a++);. Don't go into macros. They'll save you few keystrokes and then add 100x that if you ever need to debug that loop.

                Q Offline
                Q Offline
                Q139
                wrote on last edited by Q139
                #7

                @Chris-Kawa Why would it be significantly harder to debug?

                Chris KawaC 1 Reply Last reply
                0
                • Q Q139

                  @Chris-Kawa Why would it be significantly harder to debug?

                  Chris KawaC Offline
                  Chris KawaC Offline
                  Chris Kawa
                  Lifetime Qt Champion
                  wrote on last edited by Chris Kawa
                  #8

                  @Q139 I overshot with the 100x for dramatic effect ;) It's harder because you can clearly see the current value of a in the debugger (it's even in the tooltip on hover in QtCreator or VS). With macro you can do it too of course, but if you see the macro for the first time it looks like a function, so you need to go to its implementation, look up what's the name of the counter variable and then look that up in the debugger.
                  There's also the readability problem. Remember that you'll write this once and then it will be read a lot of times so making it readable should take priority over saving few keystrokes now and then. Most IDEs even have a snippet for this so you can make a for loop with a shortcut so that's not even saving you from typing that much.
                  Your example also shows another problem with this. To use the counter in the for body you need to know that the macro defines a counter that is called i. If you don't know that you need to look it up and someone reading it doesn't know what i is at first glance. Also "Go to definition" will take you to the macro invocation which is just not helpful.

                  I just can't see any compelling reason to use a macro in this case. What does it give you or your readers?

                  Q 1 Reply Last reply
                  2
                  • Chris KawaC Chris Kawa

                    @Q139 I overshot with the 100x for dramatic effect ;) It's harder because you can clearly see the current value of a in the debugger (it's even in the tooltip on hover in QtCreator or VS). With macro you can do it too of course, but if you see the macro for the first time it looks like a function, so you need to go to its implementation, look up what's the name of the counter variable and then look that up in the debugger.
                    There's also the readability problem. Remember that you'll write this once and then it will be read a lot of times so making it readable should take priority over saving few keystrokes now and then. Most IDEs even have a snippet for this so you can make a for loop with a shortcut so that's not even saving you from typing that much.
                    Your example also shows another problem with this. To use the counter in the for body you need to know that the macro defines a counter that is called i. If you don't know that you need to look it up and someone reading it doesn't know what i is at first glance. Also "Go to definition" will take you to the macro invocation which is just not helpful.

                    I just can't see any compelling reason to use a macro in this case. What does it give you or your readers?

                    Q Offline
                    Q Offline
                    Q139
                    wrote on last edited by Q139
                    #9

                    @Chris-Kawa
                    Defining variable name to macro might help readability if debugger displays variables well.

                    #define afor(v,max) for(int v=0; v<max; v++)
                    
                    afor(i,3)
                        infoLine(n(c[i]));
                    

                    Was also looking into macros support for text manipulation to make macro like afor(i=1,3)but it appears only avalible option is ## that appends text of macro function parameters
                    So just replaced = with comma and used 3 paramaters

                    #define afor(v,min,max) for(int v=min; v<max; v++)
                    
                    afor(i,1,3)
                    

                    Qt debugger displays variable value easyer now.
                    Only problem is that if i have 2 or more #defines with same name but dif argument lengths it wont find correct macro by arg length, it chooses last defined one.

                    Chris KawaC 1 Reply Last reply
                    0
                    • Q Q139

                      @Chris-Kawa
                      Defining variable name to macro might help readability if debugger displays variables well.

                      #define afor(v,max) for(int v=0; v<max; v++)
                      
                      afor(i,3)
                          infoLine(n(c[i]));
                      

                      Was also looking into macros support for text manipulation to make macro like afor(i=1,3)but it appears only avalible option is ## that appends text of macro function parameters
                      So just replaced = with comma and used 3 paramaters

                      #define afor(v,min,max) for(int v=min; v<max; v++)
                      
                      afor(i,1,3)
                      

                      Qt debugger displays variable value easyer now.
                      Only problem is that if i have 2 or more #defines with same name but dif argument lengths it wont find correct macro by arg length, it chooses last defined one.

                      Chris KawaC Offline
                      Chris KawaC Offline
                      Chris Kawa
                      Lifetime Qt Champion
                      wrote on last edited by Chris Kawa
                      #10
                      afor(i,1,3)
                      

                      vs

                      for(int i=1; i<3; ++i)
                      

                      Just my personal opinion but I think you're overdoing it. It's just not worth it. afor looks like atoi or some such function. It's misleading. It hinders even basic tasks like scanning visually for loops and whiles when you're looking for basic complexity markers in your code.
                      I mean go through say 50 random projects on github. I bet you none of them will try to obscure a for loop, basic language construct.

                      1 Reply Last reply
                      6
                      • S Offline
                        S Offline
                        SimonSchroeder
                        wrote on last edited by
                        #11

                        @Q139 The general advice is to not use any macros in your code. There are a few exceptions to this rule. I personally like X macros for a few use cases. Also if I have a lot of repeated code that cannot be easily factored out into a function (switch over enums and types, ...) I do use macros. Repeated similar code also appears when overloading operator+, operator- and so on for a user-defined type.

                        However, in your case you are using a macro afor to introduce new syntax. This will make your code unreadable for anybody else (possibly also include the very popular 'future self').

                        The major question usually is if you really need the running index. For your tiny example iteration over infoLine(n(c[i])) you can rewrite it to a range-based for loop:

                        for(const auto &a : c)
                            infoLine(n(a));
                        

                        There are few cases where you actually need an actual index. C++20 helps out with this a little bit. You can now write:

                        for(int i = 0; const auto &a : c)
                        {
                            infoLine(n(a));
                            ...
                            ++i;
                        }
                        

                        Personally, with a all the new features of C++20, like ranges and generators, I would really like to see someone implement something like this:

                        for(int i : "[0..10)"_rng) // numbers 0 through 9
                            ...
                        for(int i : "[1..10]"_rng) // numbers 1 through 10
                            ...
                        
                        kshegunovK Chris KawaC 2 Replies Last reply
                        1
                        • fcarneyF Offline
                          fcarneyF Offline
                          fcarney
                          wrote on last edited by
                          #12

                          If you really want ranges then use boost:range
                          C++ will eventually get ranges. So you are future proofing your code for minimal changes.

                          C++ is a perfectly valid school of magic.

                          1 Reply Last reply
                          0
                          • S SimonSchroeder

                            @Q139 The general advice is to not use any macros in your code. There are a few exceptions to this rule. I personally like X macros for a few use cases. Also if I have a lot of repeated code that cannot be easily factored out into a function (switch over enums and types, ...) I do use macros. Repeated similar code also appears when overloading operator+, operator- and so on for a user-defined type.

                            However, in your case you are using a macro afor to introduce new syntax. This will make your code unreadable for anybody else (possibly also include the very popular 'future self').

                            The major question usually is if you really need the running index. For your tiny example iteration over infoLine(n(c[i])) you can rewrite it to a range-based for loop:

                            for(const auto &a : c)
                                infoLine(n(a));
                            

                            There are few cases where you actually need an actual index. C++20 helps out with this a little bit. You can now write:

                            for(int i = 0; const auto &a : c)
                            {
                                infoLine(n(a));
                                ...
                                ++i;
                            }
                            

                            Personally, with a all the new features of C++20, like ranges and generators, I would really like to see someone implement something like this:

                            for(int i : "[0..10)"_rng) // numbers 0 through 9
                                ...
                            for(int i : "[1..10]"_rng) // numbers 1 through 10
                                ...
                            
                            kshegunovK Offline
                            kshegunovK Offline
                            kshegunov
                            Moderators
                            wrote on last edited by
                            #13

                            @SimonSchroeder said in Simplest way to for loop:

                            Personally, with a all the new features of C++20, like ranges and generators, I would really like to see someone implement something like this:
                            for(int i : "[0..10)"_rng) // numbers 0 through 9
                            ...
                            for(int i : "[1..10]"_rng) // numbers 1 through 10
                            ...

                            Ah, the C++ code is JavaScript argument. Well, I really wish someone wouldn't. auto is terrible enough on its own, I personally don't need even more vague headaches.

                            Read and abide by the Qt Code of Conduct

                            1 Reply Last reply
                            0
                            • S SimonSchroeder

                              @Q139 The general advice is to not use any macros in your code. There are a few exceptions to this rule. I personally like X macros for a few use cases. Also if I have a lot of repeated code that cannot be easily factored out into a function (switch over enums and types, ...) I do use macros. Repeated similar code also appears when overloading operator+, operator- and so on for a user-defined type.

                              However, in your case you are using a macro afor to introduce new syntax. This will make your code unreadable for anybody else (possibly also include the very popular 'future self').

                              The major question usually is if you really need the running index. For your tiny example iteration over infoLine(n(c[i])) you can rewrite it to a range-based for loop:

                              for(const auto &a : c)
                                  infoLine(n(a));
                              

                              There are few cases where you actually need an actual index. C++20 helps out with this a little bit. You can now write:

                              for(int i = 0; const auto &a : c)
                              {
                                  infoLine(n(a));
                                  ...
                                  ++i;
                              }
                              

                              Personally, with a all the new features of C++20, like ranges and generators, I would really like to see someone implement something like this:

                              for(int i : "[0..10)"_rng) // numbers 0 through 9
                                  ...
                              for(int i : "[1..10]"_rng) // numbers 1 through 10
                                  ...
                              
                              Chris KawaC Offline
                              Chris KawaC Offline
                              Chris Kawa
                              Lifetime Qt Champion
                              wrote on last edited by
                              #14

                              @SimonSchroeder said:

                              Personally, with a all the new features of C++20, like ranges and generators, I would really like to see someone implement something like this:

                              I was bored :P

                              auto operator"" _rng(const char* str, size_t len)
                              {
                                  int start = atoi(str+1);
                                  int end = atoi(strrchr(str, '.') + 1);
                              
                                  if (*str == '(') ++start;
                                  if (*(str+len-1) == ']') ++end;
                              
                                  return ranges::views::iota(start, end);
                              }
                              
                              int main()
                              {
                                  for (auto i : "[1..10)"_rng)
                                  {
                                      std::cout << i << '\n';
                                  }
                              }
                              

                              Please don't ever use this anywhere. No, seriously. It's a horrible waste.

                              1 Reply Last reply
                              4
                              • Q Offline
                                Q Offline
                                Q139
                                wrote on last edited by Q139
                                #15
                                #define el(t) errorLine(t)
                                #define il(t) infoLine(t)
                                #define vo void
                                #define re return
                                #define ei   else if
                                #define el   else
                                #define w(c)             while(c)
                                //for loops zero index based
                                #define f0(v,max)        for(int v=0; v<max; v++)
                                #define f(v,min,max)     for(int v=min; v<max; v++)
                                #define fRev(v,min,max)  for(int v=max-1; v>=min; v--)
                                #define fa(v,c)          for(auto v:c)
                                //data types
                                #define D double
                                #define F float
                                //int types
                                #define I int
                                #define UI unsigned int
                                #define L long int
                                #define UL unsigned long int
                                #define I64 qint64
                                #define I32 qint32
                                #define I16 qint16
                                #define U64 quint64
                                #define U32 quint32
                                #define U16 quint16
                                
                                #define C char
                                #define UC unsigned char
                                #define B bool
                                

                                I tryed coding with those , in some places i think it can actually increase readability ,if familiar with the macros.
                                Also single letter capital variable types make code look cleaner.
                                If i continue adding stuff some point 1-2 letter combos will run out and will have to start using more keystrokes.

                                JonBJ kshegunovK 2 Replies Last reply
                                0
                                • Q Q139
                                  #define el(t) errorLine(t)
                                  #define il(t) infoLine(t)
                                  #define vo void
                                  #define re return
                                  #define ei   else if
                                  #define el   else
                                  #define w(c)             while(c)
                                  //for loops zero index based
                                  #define f0(v,max)        for(int v=0; v<max; v++)
                                  #define f(v,min,max)     for(int v=min; v<max; v++)
                                  #define fRev(v,min,max)  for(int v=max-1; v>=min; v--)
                                  #define fa(v,c)          for(auto v:c)
                                  //data types
                                  #define D double
                                  #define F float
                                  //int types
                                  #define I int
                                  #define UI unsigned int
                                  #define L long int
                                  #define UL unsigned long int
                                  #define I64 qint64
                                  #define I32 qint32
                                  #define I16 qint16
                                  #define U64 quint64
                                  #define U32 quint32
                                  #define U16 quint16
                                  
                                  #define C char
                                  #define UC unsigned char
                                  #define B bool
                                  

                                  I tryed coding with those , in some places i think it can actually increase readability ,if familiar with the macros.
                                  Also single letter capital variable types make code look cleaner.
                                  If i continue adding stuff some point 1-2 letter combos will run out and will have to start using more keystrokes.

                                  JonBJ Offline
                                  JonBJ Offline
                                  JonB
                                  wrote on last edited by JonB
                                  #16

                                  @Q139
                                  I don't mean to be rude, and of course your code is up to you, but I think you will be the only person to find these macros "clearer". I would simply class them as "dangerous" --- goodness knows what you might "break" by defining single- or even two-character sequences as macros. And you are overloading, say, el versus el(t) to do completely different things. On top of everything, have you looked whether you will break, say, Qt Creator's auto-completion or folding etc. with these definitions?

                                  This is just not the C++ way to do things. Up to you.

                                  1 Reply Last reply
                                  8
                                  • Q Q139
                                    #define el(t) errorLine(t)
                                    #define il(t) infoLine(t)
                                    #define vo void
                                    #define re return
                                    #define ei   else if
                                    #define el   else
                                    #define w(c)             while(c)
                                    //for loops zero index based
                                    #define f0(v,max)        for(int v=0; v<max; v++)
                                    #define f(v,min,max)     for(int v=min; v<max; v++)
                                    #define fRev(v,min,max)  for(int v=max-1; v>=min; v--)
                                    #define fa(v,c)          for(auto v:c)
                                    //data types
                                    #define D double
                                    #define F float
                                    //int types
                                    #define I int
                                    #define UI unsigned int
                                    #define L long int
                                    #define UL unsigned long int
                                    #define I64 qint64
                                    #define I32 qint32
                                    #define I16 qint16
                                    #define U64 quint64
                                    #define U32 quint32
                                    #define U16 quint16
                                    
                                    #define C char
                                    #define UC unsigned char
                                    #define B bool
                                    

                                    I tryed coding with those , in some places i think it can actually increase readability ,if familiar with the macros.
                                    Also single letter capital variable types make code look cleaner.
                                    If i continue adding stuff some point 1-2 letter combos will run out and will have to start using more keystrokes.

                                    kshegunovK Offline
                                    kshegunovK Offline
                                    kshegunov
                                    Moderators
                                    wrote on last edited by
                                    #17

                                    @Q139 said in Simplest way to for loop:

                                    I tryed coding with those , in some places i think it can actually increase readability ,if familiar with the macros.

                                    @JonB said in Simplest way to for loop:

                                    This is just not the C++ way to do things.

                                    This is not even the C way to do things, that's simply trying to reinvent the language by means of the preprocessor, what could possibly go wrong ...

                                    Read and abide by the Qt Code of Conduct

                                    1 Reply Last reply
                                    5
                                    • Chris KawaC Offline
                                      Chris KawaC Offline
                                      Chris Kawa
                                      Lifetime Qt Champion
                                      wrote on last edited by
                                      #18

                                      Reminds me of a guy that transitioned form Pascal to C++ and first thing he did was define bunch of macros like

                                      #define begin {
                                      #define end }
                                      #define procedure void
                                      

                                      If you decided to code in C++ code in C++. I completely agree with @kshegunov . Using preprocessor to reinvent the language is just straight up horrible.

                                      artwawA 1 Reply Last reply
                                      6
                                      • Chris KawaC Chris Kawa

                                        Reminds me of a guy that transitioned form Pascal to C++ and first thing he did was define bunch of macros like

                                        #define begin {
                                        #define end }
                                        #define procedure void
                                        

                                        If you decided to code in C++ code in C++. I completely agree with @kshegunov . Using preprocessor to reinvent the language is just straight up horrible.

                                        artwawA Offline
                                        artwawA Offline
                                        artwaw
                                        wrote on last edited by
                                        #19

                                        @Chris-Kawa I used to code a lot in Borland Pascal + TASM back in '90 but I would not even consider such... THING as the above. That's truly WAT moment for me.

                                        For more information please re-read.

                                        Kind Regards,
                                        Artur

                                        1 Reply Last reply
                                        2
                                        • Q Offline
                                          Q Offline
                                          Q139
                                          wrote on last edited by Q139
                                          #20

                                          @JonB said in Simplest way to for loop:

                                          On top of everything, have you looked whether you will break, say, Qt Creator's auto-completion or folding etc. with these definitions?
                                          Project 35k lines ,no problems so far.

                                          If I continue adding macros at some point I would need a converter to detect the macros and convert to clean code.

                                          It is sad that precompiler fails if adding other preprocessor macros like #define ompFor #pragma omp parrallel for schedule(dynamic)

                                          mrjjM 1 Reply Last reply
                                          0

                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved