Getting started
Function pointers
Operators
Data types
Arrays
Undefined behavior
Random numbers
Preprocessor and macros
Signal handling
Variable arguments
Files and I/O streams
Assertion
Linked lists
Generic selection
X-macros
Function parameters
Pointers
Structs
Sequence points
Command-line arguments
Aliasing and effective type
Compilation
Identifier scope
Bit-fields
Strings
Comman pitfalls
Error handling
Implicit and explicit conversions
Type qualifiers
Valgrind
Typedef
Selection statements
Declaration vs. definitio
Standard math
Boolean
Literals for numbers, characters and strings
Storage classes
Declarations
Formatted Input/Output
Compound literals
Inline assembly
Threads native
Initialization
Structure padding and packing
Memory management
Implementation-defined behaviour
Atomics
Iteration statements, loops, for, while, do-while
Enumerations
Jump Statements
Create and include header files
Testing frameworks
ctype.h characters classification
Pass 2D-arrays to functions
Side effects
Multi-character character sequences
Constrains
Inlining
Unions
Multi-threading
Common idioms and developer practices
Inter-process communication (IPC)
Comments
Contributors

Mixing signed and unsigned integers in arithmetic operations

suggest change

It is usually not a good idea to mix signed and unsigned integers in arithmetic operations. For example, what will be output of following example?

#include <stdio.h>

int main(void)
{ 
    unsigned int a = 1000;
    signed int b = -1;

    if (a > b) puts("a is more than b");
    else puts("a is less or equal than b"); 

    return 0;
}

Since 1000 is more than -1 you would expect the output to be a is more than b, however that will not be the case.

Arithmetic operations between different integral types are performed within a common type defined by the so called usual arithmetic conversions (see the language specification, 6.3.1.8).

In this case the “common type” is unsigned int, Because, as stated in Usual arithmetic conversions,

714  Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

This means that int operand b will get converted to unsigned int before the comparison.

When -1 is converted to an unsigned int the result is the maximal possible unsigned int value, which is greater than 1000, meaning that a > b is false.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents