Sum of two chars in C/C++
Because although a
and b
are each of type char
, the expression a + b
is of type int
. Anytime you do math with char types, they are converted to int before doing the actual calculations.
Sum of two characters
Sadly, it won't give an error message. As is common with C, instead of errors it has "undefined behavior", which makes debugging a lot of problems difficult, because it is syntactically valid but technically wrong. This is a lot of the reason why exceptions were added in C++, but this is getting off topic.
As mentioned in comments, 'a' + 'b' is in fact 195, which in octal is 303. Reinterpreting the unsigned 195 to a signed value is -61 (see below for more on this). In both cases, they are outside of the printable range for ascii characters. On my console it prints a � but this is non-standard, different consoles will print different things there.
The fix is to make sure you are passing meaningful data to printf before calling it, and no expecting printf to do the work of detecting it.
Side note: you should turn on all warnings with your compiler, they often catch many of these problems.
Side note 2: if 'a' + 'b' yielded a signed char
, then it would be -61, but it in fact is a 32 bit int. You can check this with sizeof('a' + 'b')
returning 4. So the number being printed is 195, which still doesn't map to a valid character in the ASCII table.
Addition of two chars produces int
What you're seeing is the result of the so-called "usual arithmetic conversions" that occur during arithmetic expressions, particularly those that are binary in nature (take two arguments).
This is described in §5/9:
Many binary operators that expect operands of arithmetic or enumeration type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions, which are defined as follows:
— If either operand is of type
long double
, the other shall be converted tolong double
.
— Otherwise, if either operand isdouble
, the other shall be converted todouble
.
— Otherwise, if either operand isfloat
, the other shall be converted tofloat
.
— Otherwise, the integral promotions (4.5) shall be performed on both operands.54)
— Then, if either operand isunsigned long
the other shall be converted tounsigned long
.
— Otherwise, if one operand is along int
and the otherunsigned int
, then if along int
can represent all the values of anunsigned int
, theunsigned int
shall be converted to along int
; otherwise both operands shall be converted tounsigned long
.
int
— Otherwise, if either operand islong
, the other shall be converted tolong
.
— Otherwise, if either operand isunsigned
, the other shall be converted tounsigned
.[Note: otherwise, the only remaining case is that both operands are
int
]
The promotions alluded to in §4.5 are:
1 An rvalue of type
char
,signed char
,unsigned char
,short int
, orunsigned short int
can be converted to an rvalue of typeint
ifint
can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of typeunsigned int
.2 An rvalue of type
wchar_t
(3.9.1) or an enumeration type (7.2) can be converted to an rvalue of the first of the following types that can represent all the values of its underlying type:int
,unsigned int
,long
, orunsigned long
.3 An rvalue for an integral bit-field (9.6) can be converted to an rvalue of type
int
ifint
can represent all the values of the bit-field; otherwise, it can be converted tounsigned int
ifunsigned int
can represent all the values of the bit-field. If the bit-field is larger yet, no integral promotion applies to it. If the bit-field has an enumerated type, it is treated as any other value of that type for promotion purposes.4 An rvalue of type
bool
can be converted to an rvalue of typeint
, withfalse
becoming zero andtrue
becomingone
.5 These conversions are called integral promotions.
From here, sections such as "Multiplicative operators" or "Additive operators" all have the phrase: "The usual arithmetic conversions are performed..." to specify the type of the expression.
In other words, when you do integral arithmetic the type is determined with the categories above. In your case, the promotion is covered by §4.5/1 and the type of the expressions are int
.
Addition of two character literals in c++
With ASCII encoding the values of '9'
and '5'
is 57
and 53
(respectively).
57 + 53
is equal to 110
.
What you're adding is the encoded values of the characters, not their digits.
And you get the output 110
(instead of the ASCII character 'n'
which have the value 110
) because the addition causes the characters to be promoted to int
values and the result is an int
value that is not converted to a char
.
Trying to write a program to sum the value of an int and a char
int cs = sum(c, ch - 0);
It looks like your trying to account for ASCII values by subtracting the ASCII value of 0 from whatever character the user enters. However, you used an integer literal of 0, when you'd want to use a character literal of '0'. See below:
int cs = sum(c, ch - '0');
Also, I would recommend renaming your int to i or something other than c. It's a little difficult to distinguish that the types of c and ch are different.
Also consider changing
if((c >= '0' && c <= '9')
to
if((c >= 0 && c <= 9)
c is an integer and you should compare it as such. By using ' ', you're basically doing a cast to a char variable which is unnecessary here.
Another problem is that I don't think you're going to be able to accomplish what you're trying to do using a char variable for a two-digit number. A char variable can hold a single character, where as a two-digit number is composed of, well, two characters.
Sum of two chars in Kotlin
According to the documentation this is not possible if the operation is done just relying on Kotlin's type inference.
'A' + 'B' can be written as 'A'.plus('B'), but the addition operator (.plus) for Char only accepts Int in the second parcel.
One way to make this operation work would be 'A' + 'B'.toInt(), but it still wouldn't print a legal answer, because the sum of the values 'A' = 65 and 'B' = 66 doesn't exist in the ASCII table.
In Java, is the result of the addition of two chars an int or a char?
The result of adding Java chars, shorts, or bytes is an int:
Java Language Specification on Binary Numeric Promotion:
- If any of the operands is of a reference type, unboxing conversion
(§5.1.8) is performed. Then:- If either operand is of type double, the
other is converted to double.- Otherwise, if either operand is of type
float, the other is converted to float.- Otherwise, if either operand
is of type long, the other is converted to long.- Otherwise, both
operands are converted to type int.
But note what it says about compound assignment operators (like +=):
The result of the binary operation is converted to the type of the left-hand variable ... and the result of the conversion is stored into the variable.
For example:
char x = 1, y = 2;
x = x + y; // compile error: "possible loss of precision (found int, required char)"
x = (char)(x + y); // explicit cast back to char; OK
x += y; // compound operation-assignment; also OK
One way you can find out the type of the result, in general, is to cast it to an Object and ask it what class it is:
System.out.println(((Object)('a' + 'b')).getClass());
// outputs: class java.lang.Integer
If you're interested in performance, note that the Java bytecode doesn't even have dedicated instructions for arithmetic with the smaller data types. For example, for adding, there are instructions iadd
(for ints), ladd
(for longs), fadd
(for floats), dadd
(for doubles), and that's it. To simulate x += y
with the smaller types, the compiler will use iadd
and then zero the upper bytes of the int using an instruction like i2c
("int to char"). If the native CPU has dedicated instructions for 1-byte or 2-byte data, it's up to the Java virtual machine to optimize for that at run time.
If you want to concatenate characters as a String rather than interpreting them as a numeric type, there are lots of ways to do that. The easiest is adding an empty String to the expression, because adding a char and a String results in a String. All of these expressions result in the String "ab"
:
'a' + "" + 'b'
"" + 'a' + 'b'
(this works because"" + 'a'
is evaluated first; if the""
were at the end instead you would get"195"
)new String(new char[] { 'a', 'b' })
new StringBuilder().append('a').append('b').toString()
String.format("%c%c", 'a', 'b')
Joining two characters in c++
A char
is not a string
. So you can first convert the first char to a string and than add the next ones like:
int main()
{
char c1 ='0';
char c2 ='4';
auto c3 = std::string(1,c1)+c2;
std::cout<< c3;
}
What is "magic" std::string(1,c1)
:
It uses the std::string constructor of the form: std::string::string (size_t n, char c);
. So it "fills" the string with one single character of your given c1 which is the 0
.
If you add chars you get the result of adding the numeric value of it which is:
int main() {
std::cout << (int)c1 << std::endl;
std::cout << (int)c2 << std::endl;
std::cout << (int)c1+c2 << std::endl;
std::cout << char(c1+c2) << std::endl;
}
The numeric value as int from 0
is 48, from 4
it is 52. Add both you get 100. And 100 is a d
in ascii coding.
Related Topics
Visual Studio 2017 Can't Find Windows.H
Read Word by Word from File in C++
Loading a File into a Vector<Char>
How to Execute Another Exe from a C++ Program in Windows
Error C2065: 'Cout':Undeclared Identifier
Comparing Std::Functions for Equality
Parameter Name Omitted, C++ VS C
Strange Ambiguous Call to Overloaded Function Error
When Should Functions Be Member Functions
What Should I Know About Structured Exceptions (Seh) in C++
How to Prevent an Object Being Created on the Heap