Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performing arithmetic with chars in C/C++

Tags:

c++

c

How does this C/C++ code work? I understood most of it but not the part specified below:

c2= (c1>='a' && c1<='z') ? ('A'+c1-'a'):c1

Especially this part:

('A'+c1-'a')

What is this part of the code doing?

Both c1 and c2 have type char.

like image 902
Gopal Sharma Avatar asked Feb 26 '14 14:02

Gopal Sharma


People also ask

Can we perform arithmetic operations on character?

Character arithmetic is used to implement arithmetic operations like addition, subtraction ,multiplication ,division on characters in C and C++ language. In character arithmetic character converts into integer value to perform task. For this ASCII value is used. It is used to perform action the strings.

Can we add two characters in C?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.


3 Answers

The code converts a lower case character to upper case. If the character isn't lower case then it returns the original character.

The expression ('A'+c1-'a') does the conversion. c1-a will give the 0-based position of the character within the alphabet. By adding this value to A you will get the upper case equivilant of c1.

Update: if c1 is 'b' then the expression c1-'a' would give 1, which is the 0-based position of 'b' in the alphabet' Adding 1 to 'A' will then give 'B'

like image 53
Sean Avatar answered Oct 14 '22 10:10

Sean


This part:

('A'+c1-'a')

changes c1 from lower case to upper case.

The whole statement:

c2= (c1>='a' && c1<='z') ? ('A'+c1-'a'):c1

says "if c1 is lower case, change it to upper case and assign that to c2; otherwise, just assign c1 to c2."

like image 2
Beta Avatar answered Oct 14 '22 09:10

Beta


char are just integer numbers. You can add do classic operations on them.

The operation will transform (if needed) a lower case char c1 into upper case char. But it is tricky and relies on the ASCII encoding to work and may not work with some specific local.

Instead I recommend using std::toupper, which takes into account the current local to perform the operation

like image 1
Davidbrcz Avatar answered Oct 14 '22 09:10

Davidbrcz