Difference between char in C and C++? [duplicate] - c++

This question already has answers here:
Why are C character literals ints instead of chars?
(11 answers)
Closed 1 year ago.
I know that C and C++ are different languages.
Code - C
#include <stdio.h>
int main()
{
printf("%zu",sizeof('a'));
return 0;
}
Output
4
Code- C++
#include <iostream>
int main()
{
std::cout<<sizeof('a');
return 0;
}
Output
1
https://stackoverflow.com/a/14822074/11862989 in this answer user Kerrek SB(438k Rep.) telling about types in C++ nor mentions char neither int but just integral.
is char in C++ is integral type or strict char type ?

is char in C++ is integral type or strict char type ?
Character types, such as char, are integral types in C++.
The type of narrow character constant in C is int, while the type of narrow character literal in C++ is char.

is char in C++ is integral type or strict char type ?
Usage of type_traits lets you know the type:
#include <iostream>
#include <type_traits>
int main()
{
std::cout << std::is_integral<char>();
}
Output:
1

As others mentioned, In C 'a' is char constant and treated as an integer.
In C++ it is integral.
Also you can check the difference between char c = 'a' and 'a' in C++ by using RTTI (run time type info) as follows:
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
char c = 'a';
// Get the type info using typeid operator
const type_info& ti2 = typeid('a');
const type_info& ti3 = typeid(c);
// Check if both types are same
if (ti2 != ti3)
cout << "different type" << endl;
else
cout << "same type"<< endl;
return 0;
}
The output is : same type.
However, char c = 'a' and 'a' are NOT same in C.

Related

C++ can't compare string position and int [duplicate]

This question already has answers here:
Explain integer comparison with promotion
(2 answers)
Does it matter if I don't explicitly cast an int to a char before comparison with a char?
(2 answers)
Closed 3 months ago.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string codigo = "12345678917";
int remainder = 7;
if (remainder == codigo[10]) {
cout<<"equal" << endl;
}
return 0;
}
It's just a simple comparison. This code doesnt print "equal".
I changed the type of the int to char or string but it didnt work. I tried comparison methods and still nothing. Am missing something here?
It did work when i changed remainder to '7'. But idk why comparing with variable doesnt work
in your code you are comparing an int to a char, in this situation there will be an implicit conversion from char to int.
using
cout << "int value: " << (int)codigo[10] << endl;
you can see that the int value of the character is 55, as 7 does not equal 55 the condition will not be true.
It also won't work if you just change the type to char as this will cast 7 to a char which is not the character '7'.
Using single quotes around the 7 causes the value to be a character literal, as it is stored in an int its value will be 55. Since this is equal to the character value of codigo[10] the condition will be true.

How do I create an array of pointers of type char C++?

I'm not very familiar with pointers, but I have an assignment that requires me to create an array of pointers of type char. I just can't seem to get the code running.
#include <iostream>
using namespace std;
int main() {
int n = 0;
char *seasons[] = { "Winter",
"Spring",
"Summer",
"Fall"};
cout << seasons[n] << endl;
return 0;
}
I copied and pasted this code from the textbook, but I keep getting errors for the strings that are in the array.
The error is E0144: a value of type "const char *" cannot be used to initialize an entity of type "char *"
I wonder if your textbook-maker did a quick-and-dirty conversion of existing C code to C++. In C, string literals are arrays of type char (even though they are immutable), but in C++ they are arrays of type const char.
The solution here is to change the type of seasons to be const char *[] to make an array of pointers to these const char arrays:
const char *seasons[] = { "Winter",
"Spring",
"Summer",
"Fall"};
As an aside, I am also not a fan of your book doing using namespace std;. It pollutes the global namespace with the entirety of the std namespace which can (and in my experience has) lead to conflicts that will break code.

What does the typeid(var_name).name() function returns in C++?

I used the typeid(var).name() function under #include <typeinfo> header file and I saw that it returns only a character.
eg.
#include <iostream>
#include <typeinfo>
int main()
{
std::cout << typeid(5).name() << std::endl;
std::cout << typeid(5.8).name() << std::endl;
return 0;
}
output:
i
d
So, it clearly returns character.
Now I'm trying another program where the error coming is:
type.cpp:8:46: error: ISO C++ forbids comparison between pointer and integer [-fpermissive]
if(typeid((-1 + sqrt(1 - 8 * t)) / 2).name() == 'i')
and the program is:
#include <math.h>
#include <iostream>
#include <typeinfo>
int main()
{
int t;
std::cin >> t;
if(typeid((-1 + sqrt(1 - 8 * t)) / 2).name() == 'i')
std::cout << "YES";
else
std::cout << "NO";
return 0;
}
Why am I getting this error?
Member function name returns pointer of type const char * while you are trying to compare it with an object of type char that due to the integer promotion is converted to type int.
if( typeid((-1+sqrt(1-8*t))/2).name() == 'i' )
^^^^
char converted to int
So the compiler issues an error.
You could use standard function std::strcmp declared in header <cstring>. For example
if( std::strcmp( typeid((-1+sqrt(1-8*t))/2).name(), "i" ) == 0 )
However it is implementation-defined what string is generated by the function name.
typeid returns a std::type_info object and std::type_info::name returns const char* (a pointer). If this const char* points to an array containing one character and a NUL terminator, it will print the same way as single char.
The point is, you can't compare const char* with char. The function for comaring c-style string (with c-style string) is std::strcmp.
But... this is not a use-case for typeid. The type of the expression:
(-1 + sqrt(1 - 8 * t)) / 2)
is known at compile-time and does not change at runtime depending on its value. It will be always float. Note that you can check types (at compile time) with this:
std::is_integral<decltype((-1 + sqrt(1 - 8 * t)) / 2)>::value
The expression within decltype does not need to be evaluated (and it can't be) to get the type of an expression.
However, you essentially want this.

std::string comparison, lexicographical or not

The following code, comes from the article C++ quirks, part 198276
include <iostream>
#include <string>
using namespace std;
int main()
{
std::string a = "\x7f";
std::string b = "\x80";
cout << (a < b) << endl;
cout << (a[0] < b[0]) << endl;
return 0;
}
Surprisingly the output is
1
0
Shouldn't string comparison be lexicographical ? If yes how is the output explained?
There is nothing in the C++ specification to say if char is signed or unsigned, it's up to the compiler. For your compiler it seems that char defaults to signed char which is why the second comparison returns false.
So I'm just going to quote directly from your link:
It turns out that this behavior is required by the standard, in section 21.2.3.1 [char.traits.specializations.char]: “The two-argument members eq and lt shall be defined identically to the built-in operators == and < for type unsigned char .”
So:
(a < b) is required to use unsigned char comparisons.
(a[0] < b[0]) is required to use char comparisons, which may or may not be signed.

C++ passing/accessing matrix by pointers [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
2D arrays with C++
Hi, I'm trying to copy a pointer to a matrix that i'm passing in to a function in C++. here's what my code is trying to express
#include <iostream>
using namespace std;
void func( char** p )
{
char** copy = p;
cout << **copy;
}
int main()
{
char x[5][5];
x[0][0] = 'H';
func( (char**) &x);
return 0;
}
However, this gives me a Seg Fault. Would someone please explain (preferrably in some detail) what underlying mechanism i'm missing out on? (and the fix for it)
Thanks much in advance :)
A pointer to an array of 5 arrays of 5 char (char x[5][5]) has the type "pointer to array of 5 arrays of 5 chars", that is char(*p)[5][5]. The type char** has nothing to do with this.
#include <iostream>
using namespace std;
void func( char (*p)[5][5] )
{
char (*copy)[5][5] = p;
cout << (*copy)[0][0];
}
int main()
{
char x[5][5];
x[0][0] = 'H';
func(&x);
return 0;
}
Of course there are many other ways to pass a 2D array by reference or pointer, as already mentioned in comments. The most in-detail reference is probably StackOverflow's own C++ FAQ, How do I use arrays in C++?
char** is a pointer to a pointer (or an array of pointers). &x is not one of those - it's a pointer to a two-dimensional array of chars, which can be implicitly converted to a pointer to a single char (char *). The compiler probably gave you an error, at which point you put in the cast, but the compiler was trying to tell you something important.
Try this instead of using a char**:
#include <iostream>
using namespace std;
void func( char* &p )
{
char* copy = p;
cout << copy[0];
}
int main()
{
char x[5][5];
x[0][0] = 'H';
func(&x[0]);
return 0;
}