Announcement

Collapse
No announcement yet.

C conversion

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • C conversion

    I like C and have written a few yards of it over the last 30 years. I also like the fast results I can get from PB! There is a downside too, I keep tripping up over PB's "different" use of pointers, and the lack of ++, --, +=, -= operators. It seems to me that these tricks can mostly be done only by the compiler (or I suppose an interpreter), though coding a replacement for prefix ++ looks easy:
    Code:
    FUNCTION plusplus( BYREF i AS LONG, OPT BYVAL n AS LONG) AS LONG
        IF n = 0 THEN
            INCR i
        ELSE
            i = i + n
        END IF
        FUNCTION = i
    END FUNCTION
    but it leaves the coder begging for more.

  • #2
    >lack of ++, --, +=, -= operators

    ???

    What about C's lack of STEP +1 (++) , STEP -1 (--) , INCR (+=) and DECR (-=) operators?

    Fair is fair!

    BTW, what 'different' use of pointers? An address is an address is an address!

    Not to mention... it's not the paintbrush, it's the artist!

    I think at least one of us must be a language bigot.
    Michael Mattias
    Tal Systems Inc. (retired)
    Racine WI USA
    [email protected]
    http://www.talsystems.com

    Comment


    • #3
      Originally posted by Michael Mattias View Post
      I think at least one of us must be a language bigot.
      ...and I think he just had a holiday, lucky fellow.

      I have no intention of getting into a "language war". Just wanted to flush out a better way of coding.

      Comment


      • #4
        >and I think he just had a holiday, lucky fellow

        Luck? No Way. I earned that vacation.

        Reminds me of the story (or is it urban legend?) of the screen star Mae West.

        Ms. West attended a party wearing a very large diamond. When one of her fellow party guests got a good look at it, all she could say was "My Goodness!".

        To which Ms. West replied, "Goodness, my dear, had nothing to do with it."
        Michael Mattias
        Tal Systems Inc. (retired)
        Racine WI USA
        [email protected]
        http://www.talsystems.com

        Comment


        • #5
          Originally posted by Michael Mattias View Post
          >lack of ++, --, +=, -= operators

          ???

          What about C's lack of STEP +1 (++) , STEP -1 (--) , INCR (+=) and DECR (-=) operators?
          What is STEP is that new, I'm only on 8.03 is that new in 8.04

          Comment


          • #6
            Originally posted by John Petty View Post
            What is STEP
            Code:
            FOR i = 1 to 100 STEP 10
            , for a full description put your cursor on STEP and press F1!

            Comment


            • #7
              less is more ?

              a=1
              b=++a

              -------

              a=1
              incr a
              b=a
              A dozen what.

              Comment


              • #8
                Originally posted by Chris Holbrook View Post
                Code:
                FOR i = 1 to 100 STEP 10
                , for a full description put your cursor on STEP and press F1!
                True Chris but it is not an operator (or instruction like Incr or Decr)!
                Also as MCM compares it to ++ Then by the logic you showed for ++ I would be upset if my loop
                For x = 0 to 100 step 10
                give these values for x
                0
                1
                11
                etc
                John
                Last edited by John Petty; 30 Mar 2008, 02:27 AM.

                Comment


                • #9
                  A basic loop by default incerments by 1.

                  For x = 1 to 100
                  next x

                  This is the loop in C Notice how it is incremented by "x++" up'd by one.
                  For (x=0; x < 10 ; x++ )


                  If you want to step it you must do like this
                  For (x=0; x < 50 ; x= x +5 )
                  A dozen what.

                  Comment


                  • #10
                    Originally posted by Michael Mayerhoffer View Post
                    For (x=0; x < 50 ; x= x +5 )
                    or
                    Code:
                     for (x=0; x < 50; x += 5)
                    or
                    Code:
                    for (x=0; x < 50;) {
                        iResult = callafn ( "hello", ++x);
                    }
                    Something like this (taken from some actual SQLITE C code) is harder to convert:
                    Code:
                     while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
                        do_stuff;
                    }
                    That ++ before the nRetry means "increment nRetry then test it". Had it been nRetry++ it would have mean "test nRetry then increment it". How would you do that in a single PB statement?

                    Comment


                    • #11
                      Originally posted by John Petty View Post
                      True Chris but it is not an operator (or instruction like Incr or Decr)
                      Apologies John, your point was subtler than I thought!

                      Comment


                      • #12
                        That ++ before the nRetry means "increment nRetry then test it". Had it been nRetry++ it would have mean "test nRetry then increment it". How would you do that in a single PB statement?
                        By setting your FOR/NEXT loop boundaries or WHILE/WEND DO/LOOP options correctly in the first place, that's how.
                        Michael Mattias
                        Tal Systems Inc. (retired)
                        Racine WI USA
                        [email protected]
                        http://www.talsystems.com

                        Comment


                        • #13

                          As MCM pointed out it is a rewrite.
                          Trying to make an operator a function in basic is not most likely best way to do something or that is the way I see it. The better approach is to look at what is going case by case and rewrite it the way the language supports.
                          There is no downside or lacking in PB, it is the lack of understanding or experience that limits its use.
                          A dozen what.

                          Comment


                          • #14
                            >For (x=0; x < 50 ; x= x +5 )


                            For (x=0; x < 50 ; x +=5 )

                            EDIT:

                            Oops, already shown above
                            hellobasic

                            Comment


                            • #15
                              Originally posted by Michael Mayerhoffer View Post
                              There is no downside or lacking in PB..
                              never said there was, just looking for a better/faster way to do things.

                              Comment


                              • #16
                                Chris,
                                English is not my first language, either is Basic.
                                I think my English needs more work
                                To me is seems that you implied having trouble with PB pointers and it PB lacks ++, --, +=, -= operators.
                                Guess that is what you call sarcasm ?
                                -
                                mike

                                Originally posted by Chris Holbrook View Post
                                I like C and have written a few yards of it over the last 30 years. I also like the fast results I can get from PB! There is a downside too, I keep tripping up over PB's "different" use of pointers, and the lack of ++, --, +=, -= operators. It seems to me that these tricks can mostly be done only by the compiler (or I suppose an interpreter), though coding a replacement for prefix ++ looks easy:
                                Code:
                                FUNCTION plusplus( BYREF i AS LONG, OPT BYVAL n AS LONG) AS LONG
                                    IF n = 0 THEN
                                        INCR i
                                    ELSE
                                        i = i + n
                                    END IF
                                    FUNCTION = i
                                END FUNCTION
                                but it leaves the coder begging for more.
                                A dozen what.

                                Comment


                                • #17
                                  Originally posted by Michael Mayerhoffer View Post
                                  Guess that is what you call sarcasm
                                  Wasn't aware of it. My only interest is in discovering better ways to code PB.

                                  Comment


                                  • #18
                                    Pointers

                                    Oh Boy! Pointers! One of my favorite topics! Why don't I just go ahead and make a fool out of myself!

                                    Lets say one allocates 16 bytes of memory somewhere/somehow and stores it in pMem...

                                    Local pMem As Dword Ptr
                                    pMem=Global/HeapAlloc/malloc(...)

                                    Now with those 16 bytes one could then store four four byte pointers to strings for which, again, one needs to allocate memory. Lets say we have these strings....

                                    szData(0)="Zero"
                                    szData(1)="One"
                                    szData(2)="Two"
                                    szData(3)="Three"

                                    In C using base pointer notation one would do this...

                                    Code:
                                    for(i=0;i<=LAST_INDEX;i++)
                                    {
                                        pMem[i]=(char*)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,strlen(szData[i])+1);
                                        if(pMem[i])
                                        {
                                           strcpy(pMem[i],szData[i]);  //Copy *szData[] strings to storage
                                           printf("%u\t%u\t\t%u\t\t%s\n",i,&pMem[i],pMem[i],pMem[i]);
                                        }
                                    }
                                    which could result in this output something like this...

                                    Code:
                                    pMem=2314720
                                    
                                                            UINT (%u)       str (%s)
                                    i       &pMem[i]        pMem[i]         pMem[i]
                                    ==================================================
                                    0       2314720         2319056         Zero
                                    1       2314724         2327912         One
                                    2       2314728         2332032         Two
                                    3       2314732         2327808         Three
                                    Now note what the notation looks like for the assignment of the four pointers
                                    into each four byte offset into pMem. The abbreviated statement starts like this...

                                    pMem[i]=(char*)HeapAlloc(....) etc.

                                    And then of course the literal strings in szData() need to be moved to the HeapAlloc() memory.

                                    Now in PowerBASIC the notation is like this...

                                    Code:
                                    For i=0 To %LAST_ELEMENT
                                      @pMem[i]=HeapAlloc(hHeap,%HEAP_ZERO_MEMORY,Len(szData(i))+1)
                                      If @pMem[i] Then
                                         Poke$ Asciiz, @pMem[i], szData(i)
                                         pStr=Varptr(@pMem[i])
                                         Print i,Varptr(@pMem[i]),@pMem[i],@@pStr
                                      End If
                                    Next i
                                    Having to preface pMem[] with the '@' symbol confuses me. I deal with it, of course, but usually after a number of compile errors. This is one case (the only one I know of) where I find the C notation clearer than the PowerBASIC one. At times I've thought that I'd make a feature suggestion to allow a syntax similiar to C's, but I've always backed off from it because PowerBASIC's implementation of pointers is excellent as it stands, and I really am very impressed with it. I use pointers very heavily in my work, and have never found any problem with using them in PowerBASIC, except for my comments above.

                                    It also might be noted that to print the strings in PowerBASIC one needs to declare an extra variable not needed in C of Asciiz Ptr type. See my code above. I believe this need relates more to the characteristics of Basic's 'Print' statement than to pointers themselves.

                                    Below are two full programs showing what I have described here, the first in C and the second in PowerBASIC. The output from each follows directly after the program. I tried to make both programs as similiar as possible. The C version is a couple lines shorter than the PB version. I have typically found this to be the case, that is, exact C representations being maybe 98% of the PowerBASIC implementation. I might further point out though that any executables produced by PowerBASIC are ALWAYS much smaller than C or C++ executables.

                                    Since Chris brought up this topic of pointers I decided to post my ideas on this because I've always wondered if anyone else had similiar difficulties with this as I have.

                                    1st C Version
                                    Code:
                                    #include "Windows.h"
                                    #include <stdio.h>
                                    #define  LAST_INDEX  3
                                    
                                    int main(void)
                                    {
                                     char *szData[]={"Zero","One","Two","Three"}; // Initial test data is in szData[]
                                     char **pMem=NULL;                            //array, but for purposes of exposition        
                                     unsigned int i,j;                            //this data will be copied to dynamically allocated          
                                     HANDLE hHeap;                                //storage accessed by char pointer to pointer pMem.
                                    
                                     hHeap=GetProcessHeap();
                                     pMem=(char**)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,sizeof(char*)*(LAST_INDEX+1));
                                     if(pMem)
                                     {
                                        printf("pMem=%u\n\n",pMem);
                                        puts("                        UINT (%u)       str (%s)");
                                        puts("i       &pMem[i]        pMem[i]         pMem[i] ");
                                        puts("==================================================");
                                        for(i=0;i<=LAST_INDEX;i++)
                                        {
                                            pMem[i]=(char*)HeapAlloc(hHeap,HEAP_ZERO_MEMORY,strlen(szData[i])+1);
                                            if(pMem[i])
                                            {
                                               strcpy(pMem[i],szData[i]);  //Copy *szData[] strings to storage
                                               printf("%u\t%u\t\t%u\t\t%s\n",i,&pMem[i],pMem[i],pMem[i]);
                                            }
                                        }
                                        printf("\n");
                                        for(i=0;i<=LAST_INDEX;i++)
                                        {
                                            if(pMem[i])
                                            {  
                                               for(j=0;j<strlen(pMem[i]);j++)  //try some fancy byte 
                                                   printf("%c\t",pMem[i][j]);  // minipulations!
                                               printf("\n");
                                            }
                                        }
                                        printf("\n");
                                        for(i=0;i<=LAST_INDEX;i++)
                                        {
                                            if(pMem[i])
                                               printf("!!HeapFree(GetProcessHeap(),0,pMem[i])=%u\n",!!HeapFree(GetProcessHeap(),0,pMem[i]));
                                        }
                                        printf("\n!!HeapFree(GetProcessHeap(),0,pMem)=%u\n",!!HeapFree(GetProcessHeap(),0,pMem));
                                     }
                                     else
                                        puts("Memory Allocation Failure!");
                                     getchar();
                                    
                                     return 0;
                                    }
                                    
                                    /*                   52 lines
                                    pMem=2314720
                                    
                                                            UINT (%u)       str (%s)
                                    i       &pMem[i]        pMem[i]         pMem[i]
                                    ==================================================
                                    0       2314720         2319056         Zero
                                    1       2314724         2327912         One
                                    2       2314728         2332032         Two
                                    3       2314732         2327808         Three
                                    
                                    Z       e       r       o
                                    O       n       e
                                    T       w       o
                                    T       h       r       e       e
                                    
                                    !!HeapFree(GetProcessHeap(),0,pMem[i])=1
                                    !!HeapFree(GetProcessHeap(),0,pMem[i])=1
                                    !!HeapFree(GetProcessHeap(),0,pMem[i])=1
                                    !!HeapFree(GetProcessHeap(),0,pMem[i])=1
                                    
                                    !!HeapFree(GetProcessHeap(),0,pMem)=1
                                    */
                                    '2nd the PB Version. I tried to make it as line for line exact as possible
                                    Code:
                                    #Compile Exe                  'Program will demonstrate using pointers with
                                    #Dim All                      'PowerBASIC.  The strings 'Zero', 'One', 'Two',
                                    #Include "Win32Api.inc"       'and 'Three' are first loaded into Asciiz array
                                    %LAST_ELEMENT = 3             'szData.  This will simulate real data coming
                                                                  'into a program through such sources as files,
                                    Function PBMain() As Long     'databases, COM ports, etc.  Then a sixteen byte
                                      Local szData() As Asciiz*8  'buffer is created to store four pointers to
                                      Local pStr As Asciiz Ptr    'as yet unallocated memory.  Then memory is
                                      Local pMem As Dword Ptr     'allocated to copy the four strings to, and
                                      Local pByte As Byte Ptr     'those pointers are stored in the former 16 byte
                                      Local hHeap As Dword        'block (pMem).  The strings and various addresses
                                      Register i As Long          'are eventually output showing two levels of
                                                                  'indirection, as well as other fancy byte
                                      Redim szData(%LAST_ELEMENT) As Asciiz*8                  'minipulations
                                      szData(0)="Zero" : szData(1)="One" : szData(2)="Two" : szData(3)="Three"
                                      hHeap=GetProcessHeap()
                                      pMem=HeapAlloc(hHeap,%HEAP_ZERO_MEMORY,(%LAST_ELEMENT+1)*sizeof(pMem))
                                      If pMem Then
                                         Print "pMem="pMem : Print
                                         Print " i         Varptr(@pMem[i]   @pMem[i]     @@pStr"
                                         Print "================================================"
                                         For i=0 To %LAST_ELEMENT
                                           @pMem[i]=HeapAlloc(hHeap,%HEAP_ZERO_MEMORY,Len(szData(i))+1)
                                           If @pMem[i] Then
                                              Poke$ Asciiz, @pMem[i], szData(i)
                                              pStr=Varptr(@pMem[i])
                                              Print i,Varptr(@pMem[i]),@pMem[i],@@pStr
                                           End If
                                         Next i
                                         Print
                                         For i=0 To %LAST_ELEMENT
                                           If @pMem[i] Then
                                              [email protected][i]
                                              While @pByte
                                                Print Chr$(@pByte)+Space$(8);
                                                Incr pByte
                                              Wend
                                              Print
                                           End If
                                         Next i
                                         Print
                                         For i=0 To %LAST_ELEMENT
                                           If @pMem[i] Then
                                              Print "Abs(IsTrue(HeapFree(hHeap,0,@pMem[i])))="Abs(IsTrue(HeapFree(hHeap,0,@pMem[i])))
                                           End If
                                         Next i
                                         Print
                                         Print "Abs(IsTrue(HeapFree(hHeap,0,@pMem)))="Abs(IsTrue(HeapFree(hHeap,0,@pMem)))
                                      Else
                                         Print "Memory Allocation Failure!"
                                      End If
                                      Waitkey$
                                    
                                      PBMain=0
                                    End Function
                                    
                                    'Output   55 lines in program not counting spaces
                                    '
                                    'pMem= 1261648
                                    '
                                    ' i         Varptr(@pMem[i]   @pMem[i]     @@pStr
                                    '================================================
                                    ' 0             1261648       1282824      Zero
                                    ' 1             1261652       1282840      One
                                    ' 2             1261656       1282856      Two
                                    ' 3             1261660       1282872      Three
                                    '
                                    'Z        e        r        o
                                    'O        n        e
                                    'T        w        o
                                    'T        h        r        e        e
                                    '
                                    'Abs(IsTrue(HeapFree(hHeap,0,@pMem[i])))= 1
                                    'Abs(IsTrue(HeapFree(hHeap,0,@pMem[i])))= 1
                                    'Abs(IsTrue(HeapFree(hHeap,0,@pMem[i])))= 1
                                    'Abs(IsTrue(HeapFree(hHeap,0,@pMem[i])))= 1
                                    '
                                    'Abs(IsTrue(HeapFree(hHeap,0,@pMem)))= 1
                                    Fred
                                    "fharris"+Chr$(64)+"evenlink"+Chr$(46)+"com"

                                    Comment


                                    • #19
                                      PB is easier

                                      I program professional in C/C++ and the PB text is cleaner and easier to read. (IMO)

                                      I think the use of the @ (At) symbol even keeps my mind more clearly on the fact that its a pointer. The value isnt the variable, but what its pointing AT.

                                      Maybe it's me, but PB is simply better.


                                      Furthermore, why do you use HeapAlloc to allocate & copy strings to memory that you already have in an array. all of your references to the pMem[] can be pointer to the szData() itself.

                                      Code:
                                           For i=0 To %LAST_ELEMENT
                                                @pMem[i] = StrPtr(szData(i))
                                                pStr=Varptr(@pMem[i])
                                                Print i,Varptr(@pMem[i]),@pMem[i],@@pStr
                                           Next i

                                      And I don't think you need the pStr either. You could probably do @@pMem[i], thus cutting you down to 2 lines of PB code. (Anyone else see this?) or simply the szData(i) array itself.

                                      I know your confusion.. In C, you reference CHAR, so you have to do a pointer to a pointer to handle a string array. Within PB, (and more modern languages) strings are handled with single pointer. So you don't need to do double pointers.

                                      You already have the array of CHAR type with the first szData() that you acknowledge. You also don't need Heap/malloc because declaring a Dim szData() as string handles this automatically. Simply, filling a string with data is already a malloc + copy.

                                      FYI, Using HeapAlloc also subjects you to Windows virtual memory. Using your own memory management will give you total control. (each has benefits, choose which is best for you app.)

                                      Tye
                                      Last edited by Tyrone W. Lee; 31 Mar 2008, 01:26 PM.
                                      Explorations v9.10 RPG Development System
                                      http://www.explore-rpg.com

                                      Comment


                                      • #20
                                        There is a downside too, I keep tripping up over PB's "different" use of pointers, and the lack of ++, --, +=, -= operators.
                                        I like how PB does pointers, ++ and -- are no issue to me thanks to INCR, DECR like was said.

                                        But I strongly agree that += and -=, *=, ... make writing of code much easier!
                                        I am often falling to longer variable names, and it is different to type:
                                        Code:
                                        Monster.Hitpoints = Monster.Hitpoints + 10
                                        and
                                        Code:
                                        Monster.Hitpoints += 10
                                        I already sent a request to PB support on this topic, so maybe when you will do the same there will be one more reason to update PB with this "syntax".


                                        Petr
                                        [email protected]

                                        Comment

                                        Working...
                                        X