Unsigned Integer mystery

Collapse
X
 
  • Time
  • Show
Clear All
new posts

  • weaknessforcats
    replied
    Of course s1 can be negative. If it contains 0 and you --x, you have -1.

    Unfortunately, the sign bit is part of the data so you now have a really big positive number.

    That's why the loop runs forever. It should be for(x1 = 10; x1>0; x1--) to avoid the run-on.

    Leave a comment:


  • patelss23
    replied
    Originally posted by Ganon11
    I'm pretty sure you are correct.
    Thank you so much for clearing my concepts.

    Leave a comment:


  • Ganon11
    replied
    I'm pretty sure you are correct.

    Leave a comment:


  • patelss23
    replied
    Originally posted by Ganon11
    When you use the %d format specifier, you are telling printf to print that value as if it were a signed integer. Later, when your if statement checks x1-y1 (or y1-x1), you aren't telling the program to treat them as anything, so it treats the result as an unsigned integer - which cannot be less than 0.
    Thank you Ganon11.

    I got the point. That means When we compare them or use them in any expression, it will be treated as unsigned. as an example

    Code:
    unsigned int x1;
    for(x1 = 10; x1>=0; x1--){
    		printf("\nx1 = %d  : ",x1);
    	}
    This for loop will never end as x1 is unsigned and it wont be less than 0.
    m I going right way ?

    Thank you,
    Sanket

    Leave a comment:


  • Ganon11
    replied
    When you use the %d format specifier, you are telling printf to print that value as if it were a signed integer. Later, when your if statement checks x1-y1 (or y1-x1), you aren't telling the program to treat them as anything, so it treats the result as an unsigned integer - which cannot be less than 0.

    Leave a comment:


  • patelss23
    started a topic Unsigned Integer mystery

    Unsigned Integer mystery

    Hello all,
    how are you?

    let me put a code snippet here. I used microsoft vc++ 6.0 on my windows xp machine.

    /*************** *************** ****
    Code:
    unsigned int x1 = 10;
    unsigned int y1 = 20;
    
    printf("\n (x1-y1) = %d",(x1-y1));  //prints -10
    
    if((x1-y1) < 0)
      printf("\n(x1 - y1) < 0");
    else
     printf("\n(x1 - y1) > 0"); //prints (x1 - y1) > 0
    *************** *************** *******/

    Can any one please tell me what happens when we write
    printf ("\n (x1-y1) = %d",(x1-y1)); ?

    Does compiler create any temporary variable and assigns value of (x1-y1) to it?

    if yes, this temporary variable would be signed int by default ?
    if no, then why does it print (x1 - y1) > 0 ?

    Thank you in advance,
    Sanket
Working...