Hi I stumpled upon some c-code,
which syntactically is different from what I've seen before.

  1. first
    void strreverse(char* begin, char* end) {
      char aux;
      while(end>begin)
        aux=*end, *end--=*begin, *begin++=aux;
    }

    Would this be the same as

    void strreverse(char* begin, char* end) {
      char aux;
      while(end>begin){
        aux=*end;
        *end--=*begin;
        *begin++=aux;
    }
  2. second
    void itoa(int value, char* str, int base) {
            
      static char num[] = "0123456789abcdefghijklmnopqrstuvwxyz";
      char* wstr=str;
      int sign;
      div_t res;
      
    
            
      // Validate base
      if (base<2 || base>35){ *wstr='\0'; return; }
      
      // Take care of sign
      if ((sign=value) < 0) value = -value;
      
      // Conversion. Number is reversed.
      do {
        res = div(value,base);
        *wstr++ = num[res.rem];
      }while(value=res.quot);
      if(sign<0) *wstr++='-';
      *wstr='\0';
      
      // Reverse string
      strreverse(str,wstr-1);
    }

    What is happening here especially the res.quot

Thanks in advance

Recommended Answers

All 4 Replies

1) Functionally, in that situation, the two are the same. What you're seeing in the first example is C's comma operator in action. Occasionally you'll see people use it to avoid braces. Whether that's a good idea is debatable.

2) div_t is a standard structure. Do you have a more specific question about "what's happening"?

What is happening here especially the res.quot

If you mean the do...while loop,

do {
      res = div(value,base);
      *wstr++ = num[res.rem];
   }while ( value=res.quot );

when the value of res.quot -- resulting from the call to div() -- is zero, the loop ends. Or rather, the value of res.quot is assigned to value , and when value is zero the loop condition is false.

A compiler might warn about this:

warning: suggest parentheses around assignment used as truth value

div_t is struct for the result of divide operation, puts the quotient and the remainder into the structure.

it is being used here to convert a numeric value into an ascii string according to the base number system desired.

example: "itoa" convert value 1247 to be expressed as base-16 ascii string

itoa(1247,string,16);

1247 div 16 = quot 77, rem 15 ... 15 = "F"
  77 div 16 = quot  4, rem 13 ... 13 = "D"
   4 div 16 = quot  0, rem  4 ...  4 = "4"

when quot = 0, end do/while loop

final result of converting 1247 value to ascii base-16 number: "string" contains "4DF"


.

Thanks people,
very helpfull indeed.

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.