Why does long long n = 2000*2000*2000*2000; overflow? - c++

long long int n = 2000*2000*2000*2000; // overflow
long long int n = pow(2000,4); // works
long long int n = 16000000000000; // works
Why does the first one overflow (multiplying integer literal constants to assign to a long long)?
What's different about it vs. the second or third ones?

Because 2000 is an int which is usually 32-bit. Just use 2000LL.
Using LL suffix instead of ll was suggested by #AdrianMole in, now deleted, comment. Please check his answer.
By default, integer literals are of the smallest type that can hold their value but not smaller than int. 2000 can easily be stored in an int since the Standard guarantees it is effectively at least a 16-bit type.
Arithmetic operators are always called with the larger of the types present but not smaller than int:
char*char will be promoted to operator*(int,int)->int
char*int calls operator*(int,int)->int
long*int calls operator*(long,long)->long
int*int still calls operator*(int,int)->int.
Crucially, the type is not dependent on whether the result can be stored in the inferred type. Which is exactly the problem happening in your case - multiplication is done with ints but the result overflows as it is still stored as int.
C++ does not support inferring types based on their destination like Haskell does so the assignment is irrelevant.

The constants (literals) on the RHS of your first line of code are int values (not long long int). Thus, the mulitplications are performed using int arithmetic, which will overflow.
To fix this, make the constants long long using the LL suffix:
long long int n = 2000LL * 2000LL * 2000LL * 2000LL;
cppreference
In fact, as noted in the comment by Peter Cordes, the LL suffix is only actually needed on either the first (leftmost) or second constant. This is because, when multiplying types of two different ranks, the operand of lower rank is promoted to the type of the higher rank, as described here: Implicit type conversion rules in C++ operators. Furthermore, as the * (multiplication) operator has left-to-right associativity, the 'promoted' result of the first multiplication propagates that promotion to the second and third.
Thus, either of the following lines will also work without overflow:
long long int n1 = 2000LL * 2000 * 2000 * 2000;
long long int n2 = 2000 * 2000LL * 2000 * 2000;
Note: Although lowercase suffixes (as in 2000ll) are valid C++, and entirely unambiguous to the compiler, there is a general consensus that the lowercase letter, 'ell', should be avoided in long and long long integer literals, as it can easily be mistaken, by human readers, for the digit, 1. Thus, you will notice that 2000LL (uppercase suffix) has been used throughout the answers here presented.

2000*2000*2000*2000 is a multiplication of 4 int values, which returns an int value. When you assign this int value to long long int n the overflow already happend (if int is 32 bit the resulting value won't fit).
You need to make sure that the overflow does not occur, so when you write
long long int n = static_cast<long long int>(2000)*2000*2000*2000;
you make sure that you are doing a long long int multiplication (long long int multiplied with int returns a long long int, so no overflow in your case).
A shorter (and better way) is to write 2000LL or 2000ll instead of the static_cast. That gives the integer literal the right type. This is not needed for 2000 which fits into an int but it would be needed for higher values that don't fit into an int.
long long int n = 2000LL*2000*2000*2000;
long long int n = 2000LL*2000LL*2000LL*2000LL;

The other answers (as of this writing) appear to not have been explicit enough to answer the question as stated. I'll try to fill this gap.
Why does the first one overflow (multiplying integer literal constants to assign to a long long)?
The expression
long long int n = 2000*2000*2000*2000;
is evaluated as follows:
long long int n = ((2000*2000)*2000)*2000;
where the steps are (assuming 32-bit int):
(2000*2000) is a multiplication of two int values that yields 4000000, another int value.
((2000*2000)*2000) is a multiplication of the above yielded int value 4000000 with an int value 2000. This would yield 8000000000 if the value could fit into an int. But our assumed 32-bit int can store a maximum value of 231-1=2147483647. So we get overflow right at this point.
The next multiplication would happen if there hadn't been overflow above.
The assignment of the resulting int product would happen (if not the overflow) to the long long variable, which would preserve the value.
Since we did have overflow, the statement has undefined behavior, so steps 3 and 4 can't be guaranteed.
What's different about it vs. the second or third ones?
long long int n = pow(2000,4);
The pow(2000,4) converts 2000 and 4 into double (see some docs on pow), and then the function implementation does its best to produce a good approximation of the result, as a double. Then the assignment converts this double value to long long.
long long int n = 16000000000000;
The literal 16000000000000 is too large to fit into an int, so its type is instead the next signed type that can fit the value. It could be long or long long, depending on the platform. See Integer literal#The type of the literal for details. then the assignment converts this value to long long (or just writes it, if the literal's type was long long already).

The first is a multiplication using integers (typically 32 bit). It overflows because those integers cannot store 2000^4. The result is then cast to long long int.
The second calls the pow function which casts the first argument to double and returns a double. The result is then cast to long long int. There is no overflow in this case because the math is done on a double value.

You might want to use the following in C++ to understand this:
#include<iostream>
#include<cxxabi.h>
using namespace std;
using namespace abi;
int main () {
int status;
cout << __cxa_demangle(typeid(2000*2000*2000*2000).name(),0,0,&status);
}
As you can see, the type is int.
In C, you can use (courtesy of):
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#define typename(x) _Generic((x), /* Get the name of a type */ \
\
_Bool: "_Bool", unsigned char: "unsigned char", \
char: "char", signed char: "signed char", \
short int: "short int", unsigned short int: "unsigned short int", \
int: "int", unsigned int: "unsigned int", \
long int: "long int", unsigned long int: "unsigned long int", \
long long int: "long long int", unsigned long long int: "unsigned long long int", \
float: "float", double: "double", \
long double: "long double", char *: "pointer to char", \
void *: "pointer to void", int *: "pointer to int", \
char(*)[]: "pointer to char array", default: "other")
unsigned int a = 3;
int main() {
printf("%s", typename(a-10));
return 0;
}
Here the type of the expression is unsigned int because the type mismatch implicitly upgrades the type to the largest type between unsigned int and int, which is unsigned int. The unsigned int will underflow to a large positive, which will be the expected negative when assigned to or interpreted as an int. The result of the calculation will always be unsigned int regardless of the values involved.
C
The minimum default type of an integer literal without a suffix is int, but only if the literal exceeds this, does its type becomes an unsigned int; if larger than that it is given a type of a long int, therefore 2000s are all ints. The type of an expression performed on a literal however, using unary or binary operators, uses the implicit type hierarchy to decide a type, not the value of the result (unlike the literal itself which uses the length of the literal in deciding the type), this is because C uses type coercion and not type synthesis. In order to solve this, you'd have to use long suffixes ul on the 2000s to explicitly specify the type of the literal.
Similarly, the default type of a decimal literal is double, but this can be changed with a f suffix. Prefixes do not change the type of decimal or integer literals.
The type of a string literal is char [], although it is really a const char [], and is just an address of the first character in the actual representation of that string literal in .rodata, and the address can be taken like any array using the unary ampersand &"string", which is the same value (address) as "string", just a different type (char (*)[7] vs. char[7]; "string" i.e. char[] is not just (at compiler level) a pointer to the array, it is the array, whereas the unary ampersand extracts just the pointer to the array). The u prefix changes this to an array of char16_t, which is an unsigned short int; the U prefix changes it to an array of char32_t, which is an unsigned int; and the L prefix changes it to an array of wchar_t which is an int. u8 is a char and an unprefixed string uses implementation specific encoding, which is typically the same as u8 i.e. UTF-8, of which ASCII is a subset. A raw (R) prefix available only for string literals (and available only on GNU C (std=gnu99 onwards)) can be prefixed i.e. uR or u8R, but this does not influence the type.
The type of a character literal is int unless prefixed with u (u'a' is unsigned short int) or U (U'a' is unsigned int). u8 and and L are both int when used on a character literal. An escape sequence in a string or character literal does not influence the encoding and hence the type, it's just a way of actually presenting the character to be encoded to the compiler.
The type of a complex literal 10i+1 or 10j+1 is complex int, where both the real and the imaginary part can have a suffix, like 10Li+1, which in this case makes the imaginary part long and the overall type is complex long int, and upgrades the type of both the real and the imaginary part, so it doesn't matter where you put the suffix or whether you put it on both. A mismatch will always use the largest of the two suffixes as the overall type.
Using an explicit cast instead of a literal suffix always results in the correct behaviour if you use it correctly and are aware of the semantic difference that it truncates/extends (sign extends for signed; zero extends for unsigned – this is based on the type of the literal or expression being cast and not the type that's being cast to, so a signed int is sign extended into an unsigned long int) a literal to an expression of that type, rather than the literal inherently having that type.
C++
Again, the minimum default type is an int for the smallest literal base. The literal base i.e. the actual value of the literal, and the suffix influence the final literal type according to the following table where within each box for each suffix, the order of final type is listed from smallest to largest based on the size of the actual literal base. For each suffix, the final type of the literal can only be equal to or larger than the suffix type, and based on the size of the literal base. C exhibits the same behaviour. When larger than a long long int, depending on the compiler, __int128 is used. I think you could also create your own literal suffix operator i128 and return a value of that type.
The default type of a decimal literal is the same as C.
The type of a string literal is char []. The type of &"string" is const char (*) [7] and the type of +"string" is const char * (in C you can only decay using "string"+0). C++ differs in that the latter 2 forms acquire a const but in C they don't. The string prefixes behave the same as in C
Character and complex literals behave the same as C.

Related

why nvidia-smi indicates used gpu memory is less than malloced? [duplicate]

long long int n = 2000*2000*2000*2000; // overflow
long long int n = pow(2000,4); // works
long long int n = 16000000000000; // works
Why does the first one overflow (multiplying integer literal constants to assign to a long long)?
What's different about it vs. the second or third ones?
Because 2000 is an int which is usually 32-bit. Just use 2000LL.
Using LL suffix instead of ll was suggested by #AdrianMole in, now deleted, comment. Please check his answer.
By default, integer literals are of the smallest type that can hold their value but not smaller than int. 2000 can easily be stored in an int since the Standard guarantees it is effectively at least a 16-bit type.
Arithmetic operators are always called with the larger of the types present but not smaller than int:
char*char will be promoted to operator*(int,int)->int
char*int calls operator*(int,int)->int
long*int calls operator*(long,long)->long
int*int still calls operator*(int,int)->int.
Crucially, the type is not dependent on whether the result can be stored in the inferred type. Which is exactly the problem happening in your case - multiplication is done with ints but the result overflows as it is still stored as int.
C++ does not support inferring types based on their destination like Haskell does so the assignment is irrelevant.
The constants (literals) on the RHS of your first line of code are int values (not long long int). Thus, the mulitplications are performed using int arithmetic, which will overflow.
To fix this, make the constants long long using the LL suffix:
long long int n = 2000LL * 2000LL * 2000LL * 2000LL;
cppreference
In fact, as noted in the comment by Peter Cordes, the LL suffix is only actually needed on either the first (leftmost) or second constant. This is because, when multiplying types of two different ranks, the operand of lower rank is promoted to the type of the higher rank, as described here: Implicit type conversion rules in C++ operators. Furthermore, as the * (multiplication) operator has left-to-right associativity, the 'promoted' result of the first multiplication propagates that promotion to the second and third.
Thus, either of the following lines will also work without overflow:
long long int n1 = 2000LL * 2000 * 2000 * 2000;
long long int n2 = 2000 * 2000LL * 2000 * 2000;
Note: Although lowercase suffixes (as in 2000ll) are valid C++, and entirely unambiguous to the compiler, there is a general consensus that the lowercase letter, 'ell', should be avoided in long and long long integer literals, as it can easily be mistaken, by human readers, for the digit, 1. Thus, you will notice that 2000LL (uppercase suffix) has been used throughout the answers here presented.
2000*2000*2000*2000 is a multiplication of 4 int values, which returns an int value. When you assign this int value to long long int n the overflow already happend (if int is 32 bit the resulting value won't fit).
You need to make sure that the overflow does not occur, so when you write
long long int n = static_cast<long long int>(2000)*2000*2000*2000;
you make sure that you are doing a long long int multiplication (long long int multiplied with int returns a long long int, so no overflow in your case).
A shorter (and better way) is to write 2000LL or 2000ll instead of the static_cast. That gives the integer literal the right type. This is not needed for 2000 which fits into an int but it would be needed for higher values that don't fit into an int.
long long int n = 2000LL*2000*2000*2000;
long long int n = 2000LL*2000LL*2000LL*2000LL;
The other answers (as of this writing) appear to not have been explicit enough to answer the question as stated. I'll try to fill this gap.
Why does the first one overflow (multiplying integer literal constants to assign to a long long)?
The expression
long long int n = 2000*2000*2000*2000;
is evaluated as follows:
long long int n = ((2000*2000)*2000)*2000;
where the steps are (assuming 32-bit int):
(2000*2000) is a multiplication of two int values that yields 4000000, another int value.
((2000*2000)*2000) is a multiplication of the above yielded int value 4000000 with an int value 2000. This would yield 8000000000 if the value could fit into an int. But our assumed 32-bit int can store a maximum value of 231-1=2147483647. So we get overflow right at this point.
The next multiplication would happen if there hadn't been overflow above.
The assignment of the resulting int product would happen (if not the overflow) to the long long variable, which would preserve the value.
Since we did have overflow, the statement has undefined behavior, so steps 3 and 4 can't be guaranteed.
What's different about it vs. the second or third ones?
long long int n = pow(2000,4);
The pow(2000,4) converts 2000 and 4 into double (see some docs on pow), and then the function implementation does its best to produce a good approximation of the result, as a double. Then the assignment converts this double value to long long.
long long int n = 16000000000000;
The literal 16000000000000 is too large to fit into an int, so its type is instead the next signed type that can fit the value. It could be long or long long, depending on the platform. See Integer literal#The type of the literal for details. then the assignment converts this value to long long (or just writes it, if the literal's type was long long already).
The first is a multiplication using integers (typically 32 bit). It overflows because those integers cannot store 2000^4. The result is then cast to long long int.
The second calls the pow function which casts the first argument to double and returns a double. The result is then cast to long long int. There is no overflow in this case because the math is done on a double value.
You might want to use the following in C++ to understand this:
#include<iostream>
#include<cxxabi.h>
using namespace std;
using namespace abi;
int main () {
int status;
cout << __cxa_demangle(typeid(2000*2000*2000*2000).name(),0,0,&status);
}
As you can see, the type is int.
In C, you can use (courtesy of):
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
#define typename(x) _Generic((x), /* Get the name of a type */ \
\
_Bool: "_Bool", unsigned char: "unsigned char", \
char: "char", signed char: "signed char", \
short int: "short int", unsigned short int: "unsigned short int", \
int: "int", unsigned int: "unsigned int", \
long int: "long int", unsigned long int: "unsigned long int", \
long long int: "long long int", unsigned long long int: "unsigned long long int", \
float: "float", double: "double", \
long double: "long double", char *: "pointer to char", \
void *: "pointer to void", int *: "pointer to int", \
char(*)[]: "pointer to char array", default: "other")
unsigned int a = 3;
int main() {
printf("%s", typename(a-10));
return 0;
}
Here the type of the expression is unsigned int because the type mismatch implicitly upgrades the type to the largest type between unsigned int and int, which is unsigned int. The unsigned int will underflow to a large positive, which will be the expected negative when assigned to or interpreted as an int. The result of the calculation will always be unsigned int regardless of the values involved.
C
The minimum default type of an integer literal without a suffix is int, but only if the literal exceeds this, does its type becomes an unsigned int; if larger than that it is given a type of a long int, therefore 2000s are all ints. The type of an expression performed on a literal however, using unary or binary operators, uses the implicit type hierarchy to decide a type, not the value of the result (unlike the literal itself which uses the length of the literal in deciding the type), this is because C uses type coercion and not type synthesis. In order to solve this, you'd have to use long suffixes ul on the 2000s to explicitly specify the type of the literal.
Similarly, the default type of a decimal literal is double, but this can be changed with a f suffix. Prefixes do not change the type of decimal or integer literals.
The type of a string literal is char [], although it is really a const char [], and is just an address of the first character in the actual representation of that string literal in .rodata, and the address can be taken like any array using the unary ampersand &"string", which is the same value (address) as "string", just a different type (char (*)[7] vs. char[7]; "string" i.e. char[] is not just (at compiler level) a pointer to the array, it is the array, whereas the unary ampersand extracts just the pointer to the array). The u prefix changes this to an array of char16_t, which is an unsigned short int; the U prefix changes it to an array of char32_t, which is an unsigned int; and the L prefix changes it to an array of wchar_t which is an int. u8 is a char and an unprefixed string uses implementation specific encoding, which is typically the same as u8 i.e. UTF-8, of which ASCII is a subset. A raw (R) prefix available only for string literals (and available only on GNU C (std=gnu99 onwards)) can be prefixed i.e. uR or u8R, but this does not influence the type.
The type of a character literal is int unless prefixed with u (u'a' is unsigned short int) or U (U'a' is unsigned int). u8 and and L are both int when used on a character literal. An escape sequence in a string or character literal does not influence the encoding and hence the type, it's just a way of actually presenting the character to be encoded to the compiler.
The type of a complex literal 10i+1 or 10j+1 is complex int, where both the real and the imaginary part can have a suffix, like 10Li+1, which in this case makes the imaginary part long and the overall type is complex long int, and upgrades the type of both the real and the imaginary part, so it doesn't matter where you put the suffix or whether you put it on both. A mismatch will always use the largest of the two suffixes as the overall type.
Using an explicit cast instead of a literal suffix always results in the correct behaviour if you use it correctly and are aware of the semantic difference that it truncates/extends (sign extends for signed; zero extends for unsigned – this is based on the type of the literal or expression being cast and not the type that's being cast to, so a signed int is sign extended into an unsigned long int) a literal to an expression of that type, rather than the literal inherently having that type.
C++
Again, the minimum default type is an int for the smallest literal base. The literal base i.e. the actual value of the literal, and the suffix influence the final literal type according to the following table where within each box for each suffix, the order of final type is listed from smallest to largest based on the size of the actual literal base. For each suffix, the final type of the literal can only be equal to or larger than the suffix type, and based on the size of the literal base. C exhibits the same behaviour. When larger than a long long int, depending on the compiler, __int128 is used. I think you could also create your own literal suffix operator i128 and return a value of that type.
The default type of a decimal literal is the same as C.
The type of a string literal is char []. The type of &"string" is const char (*) [7] and the type of +"string" is const char * (in C you can only decay using "string"+0). C++ differs in that the latter 2 forms acquire a const but in C they don't. The string prefixes behave the same as in C
Character and complex literals behave the same as C.

Why shouldn't shorts use integer literals?

According to cppreference,
the following statement would be invalid C++:
unsigned short test = 5u;
Why is using the suffix u or U not allowed on unsigned shorts?
The code still compiles, but are there any ramifications to doing this?
5u is not of type unsigned short, but that doesn't mean that unsigned short test = 5u; is "illegal".
The usual conversions occur. As all unsigned ints are modulo 2^n for some n, this simply truncates the value on the right hand side "bit wise". So long as the rhs value fits in a short, nothing happens; if it does not, the "low order bits" are taken.
I speak about "bits" in quotes, as it is really math modulo 2^n for some value of n under the standard. Which is the same as bits, but there is no requirement that the C++ environment actually implement it using the obvious layout.
You are misreading cppreference. What it says (not in these words) is:
a literal ending in U is an unsigned int (or unsigned long int or unsigned long long int)
Note that it does not say anything about 'invalid' etc.
In your example
unsigned short test = 5u;
The 5u literal is an unsigned int.
The variable test is not an unsigned int. It is an unsigned short. The compiler inserts an implicit cast, which is perfectly legal.
That table on preference is table 6 from [lex.icon]
The reason short is not discussed is that the smallest type an integer literal can be is an int(from the suffix none part). Since an int is guaranteed to be the same size or larger than an int there is no reason to call out short.
unsigned short test = 5u;
Is valid and it will implicitly convert 5u to an unsigned short
cppreference also says:
The type of the integer literal is the first type in which the value can fit, from the list of types which depends on which numeric base and which integer-suffix was used.
This means that 5u is an unsigned int as 5 is within the range of that type.
If the value is too large, like 9887766554433u, it will be an unsigned long if that type is wider than unsigned int and can hold the value, otherwise the type will be unsigned long long.
This matters, for example, if you use auto to declare your variable:
const auto x = 9887766554433u;
Here x will be of a type sufficiently large to hold the value.

Constant integer promotion rules?

To give a little background (unrelated to the question, which will follow), in C++11 I noticed a narrowing issue:
int foo[] = { 0xFFFFFFFF };
This was failing to compile (narrowing conversion) because 0xFFFFFFFF is an unsigned int. However, I've seen cases where 0xFF is signed.
I've looked over integer promotion rules, but this is mostly within the context of lvalues and not rvalues/constants. How does the compiler determine the type of constants (without literal suffixes)? Is there documentation or a nice little table / "cheat sheet" that shows the rules for this? I'm not even really sure what this is called, otherwise I'd have attempted to find it myself in the C++11 standard.
Thanks in advance.
There's a table in the standard, which is reproduced on cppreference.com: http://en.cppreference.com/w/cpp/language/integer_literal
In particular, a hex or octal integer literal with no suffix is considered to have the first type in the following list in which its value can be represented:
int
unsigned int
long int
unsigned long int
long long int
unsigned long long int
0xFFFFFFFF is too big for int if int is 32 bits long, so unsigned int is chosen. But 0xFF fits comfortably into an int, so int it is.
What are called referred to as Integer constants in C are referred to as integer literals in C++. The rules used to determine the type of an integer literal are covered in the draft C++ standard section 2.14.2 Integer literals table 6 which says:
The type of an integer literal is the first of the corresponding list
in Table 6 in which its value can be represented.
and for Octal or hexadecimal constant with no suffix the table has the following order:
int
unsigned int
long int
unsigned long int
long long int
unsigned long long int
So 0xFF can be represented as an int while the first type that can represent 0xFFFFFFFF would be unsigned int.
The order for Decimal Constants is as follows:
int
long int
long long int
As we can see hexidecimal and octal literals behave differently, and we can see that C99 has the same table. The Rationale for International Standard—Programming Languages—C says the following about this:
Unlike decimal constants, octal and hexadecimal constants too large to
be ints are typed as unsigned int if within range of that type, since
it is more likely that they represent bit patterns or masks, which are
generally best treated as unsigned, rather than “real” numbers.
cppreference integer literal section also quotes table 6 in the The type of the literal sub-section.
0xFF is never negative. It is an alternative way of writing 255. (It has type int).
0xFFFFFFFF is a large positive number. There is a table under [lex.icon] that specifies what the type is of an integer constant. For hex constants with no suffix, it is the first type in the following list that can hold that large positive number: int, unsigned int, long int, unsigned long int, long long int, unsigned long long int. The implementation might add custom types ot this list.

Confusion in unsigned keyword in C/C++

Consider the following two C program. My question is in first program unsigned keyword prints -12 but I think it should print 4294967284 but it does not print it for %d specifier. It prints it for %u specifier. But if we look on second program, the output is 144 where it should be -112. Something is fishy about unsigned keyword which I am not getting. Any help friends!
#include <stdio.h>
int main()
{ unsigned int i = -12;
printf(" i = %d\n",i);
printf(" i = %u\n",i);
return 0;
}
Above prorgam I got from this link : Assigning negative numbers to an unsigned int?
#include <stdio.h>
int main(void)
{unsigned char a=200, b=200, c;
c = a+b;
printf("result=%d\n",c);
return 0;
}
Each printf format specifier requires an argument of some particular type. "%d" requires an argument of type int; "%u" requires an argument of type unsigned int. It is entirely your responsibility to pass arguments of the correct type.
unsigned int i = -12;
-12 is of type int. The initialization implicitly converts that value from int to unsigned int. The converted value (which is positive and very large) is stored in i. If int and unsigned int are 32 bits, the stored value will be 4294967284 (232-12).
printf(" i = %d\n",i);
i is of type unsigned int, but "%d" requires an int argument. The behavior is not defined by the C standard. Typically the value stored in i will be interpreted as if it had been stored in an int object. On most systems, the output will be i = -12 -- but you shouldn't depend on that.
printf(" i = %u\n",i);
This will correctly print the value of i (assuming the undefined behavior of the previous statement didn't mess things up).
For ordinary functions, assuming you call them correctly, arguments will often be implicitly converted to the declared type of the parameter, if such a conversion is available. For a variadic function like printf, which can take a varying number and type(s) of arguments, no such conversion can be done, because the compiler doesn't know what type is expected. Instead, arguments undergo the default argument promotions. An argument of a type narrow than int is promoted to int if int can hold all values of the type, or to unsigned int otherwise. An argument of type float is promoted to double (which is why "%f" works for both float and double arguments).
The rules are such an argument of a narrow unsigned type will often (but not always) be promoted to (signed) int.
unsigned char a=200, b=200, c;
Assuming 8-bit bytes, a and b are set to 200.
c = a+b;
The sum 400 is too bit to fit in an unsigned char. For unsigned arithmetic and conversion, out-of-range results are reduced to the range of the type. c is set to 144.
printf("result=%d\n",c);
The value of c is promoted to int; even though the argument is of an unsigned type, int is big enough to hold all possible values of the type. The output is result=144.
In the first program the behaviour is undefined. It's your responsibility to make sure that the format specifier matches the data type of the argument. The compiler emits code that assumes you got it right; at runtime it does not have to do any checks (and often, cannot do any checks even if it wanted to).
(For example, the library implementation printf function does not know what arguments you gave it , it only sees some bytes and it has to assume those are the bytes for the type that you specified using %d).
You appear to be trying to infer something unsigned means based on the output of a program with undefined behaviour. That won't work. Stick to well-defined programs (and preferably just read the definition of unsigned).
In a comment you say:
could give me any reference of unsigned keyword. Still concept is not getting cleared to me. Unsigned definition in C/C++ standard.
In the C99 standard read section 6.2.5, from part 6 onwards.
The definition of unsigned int is an integer type that can hold values from 0 up to a positive number UINT_MAX (which should be one less than a power of two), which must be at least 65535, and typically is 4294967295.
When you write unsigned int i = -12;, the compiler sees that -12 is outside of the range of permitted values for unsigned int, and it performs a conversion. The definition of that conversion is to add or subtract UINT_MAX+1 until the value is in range.
The second part of your question is unrelated to all this. There are no unsigned int in that program; only unsigned char.
In that program, 200 + 200 gives 400. As mentioned above, since this is out of range the compiler converts it by subtracting UCHAR_MAX+1 (i.e. 256) until it is in range. 400 - 256 = 144.
The %d and %u specifiers of printf have capability of (or, are responsible for) typecasting the input integer into int and unsigned int, respectively.
In fact printf (in general, any variadic functions) and arithmetic operators can accept only three types of arguments (except for the format string): 4-byte int, 8-byte long long and double (warning: very inaccurate description!) Any integral arguments whose size is less than int are extended into int. Any float arguments are extended into double. These rules improve uniformity of the input parameters of printf and arithmetic operators.
Regarding your 2nd example: the following steps take place
The + operator requires (unsigned) char operands to be extended into (unsigned) int values (which are 4-bytes integers in your case, I assume.)
The resulting sum is 400 of a 4-bytes unsigned int.
Only the least significant 1 byte of the above sum can fit into unsigned char c, so c has the value of 400 % 256 == 144.
printf requires all the smaller integral arguments to be expanded into int, thus what printf receives is 400 of a 4-bytes int.
The %d specifier prints the above argument as "400".
Google for "default argument promotion" for more details.

Why does the literal value in a type long assignment still have an 'L' at the end in C++?

Cant seem to find the answer to this, I'm sure it's simple, but just want to understand this so I can move on.
I'm looking at integer types, and am wondering why this:
long number = 645456645;
has the same effect as:
long number = 654456654L;
What is the point of using that letter 'L' at the end? Same with the 'U' for unsigned case.
I'm looking at Integer Types, and am wondering why this -
long number = 645456645;
has the same effect as -
long number = 654456654L;
Strictly speaking, the two are not equivalent.
In the former, your literal 645456645 has type int and is converted to long for the initialisation.
In the latter, it's already a long so no conversion is performed.
In this trivial example there's obviously no functional difference, but on a platform where the range of long is not the same as the range of int, you may find that you have to use the L suffix to actually get the valid literal in the first place.
The literal type specifier determines the type of the literal.
Naked integer literals always have the smallest possible int-type they fit, but with the specifier you can be explicit about the smalles type you wish to be considered:
12: int 12U: unsigned int
12L: long int 12UL: unsigned long int
12LL: long long int 12ULL: unsigned long long int
Imagine this:
template <typename T> void foo(T, T);
Now foo(12, 12L) fails because it is ambiguous, but foo(12U, 12U) works (and T is deduced as unsigned int). So literal type specifiers can be very important when you need to control the actual type of a literal expression.
It's to specify the type of the integer literal. L makes it a long and U makes it unsigned.
The use of it is cases like this:
long long number = 123456789123456;
long long number = 123456789123456LL;
Some compilers will complain about the first one since 123456789123456 doesn't fit in the default int.
The other case where it is used is to disambiguate between overloaded functions.
EDIT: (see comments)
main.cpp
int main(){
long long number = 123456789123456;
return 0;
}
Compiling it gives:
alex-desktop:~/Desktop/vm_shared> g++ main.cpp
main.cpp:3: warning: integer constant is too large for ‘long’ type
alex-desktop:~/Desktop/vm_shared>
gcc version: 4.4.3
Normally a literal such as this will be interpreted as an integer, and occasionally you want to specify a literal that is too big for an integer (> INT_MAX), in these cases you use such suffix, L and LL (U etc.), which tells the compiler to treat the literal as a long (and long long)