PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 19, 2022

[FIXED] why size_t variable, int constant comparison doesn't work properly while off_t variable works fine?

 July 19, 2022     c, casting, integer, size-t, typechecking     No comments   

Issue

I was trying to compare size_t(long int type for ubuntu) variable with int constant 0 but turned out not working properly. but off_t variable works fine.

size_t var = -3;

if(var < 0)
    putchar('X');
else
    putchar('Y');

// Y

but when I cast var into int, it works as I expect.

size_t var = -3;

if((int)var < 0)
    putchar('X');
else
    putchar('Y');

// X

but off_t(long int as well on my ubuntu) works fine without casting.

off_t var2 = -3;

if(var2 < 0)
    putchar('X');
else
    putchar('Y');

// X

Could you explain this please? Thanks.


Solution

The type size_t is an unsigned type. So when you attempt to assign the value -3 to it, the value gets converted into a very large positive value. This is why the condition in the first case is false.

In the second case, when casting var to an int, the assigned value (i.e. the very large positive value from before) is outside the range of int so it gets converted in an implementation defined manner. On most implementations, this will result the value being converted to -3, so the condition will be true.

The type off_t is a signed type so it is able to store the value -3, so the comparison works as expected.



Answered By - dbush
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing