Wann '' und wann ""
-
Hey,
Ich frage mich wann man in C++ '' oder "" benutzt,
also z.b funktionier
#define char "a"
#define char 'a' gleich
oder cout << "a"
cout << 'a'
-
Was in ' ' steht ist ein Zeichenliteral (Typ const char). Was in " " steht ist ein Zeichenkettenliteral (Typ const char[soviele zeichen wie es lang ist plus eines für die Nullterminierung]).
-
"" sind sozusagen Strings und '' sind chars.
Also z.Bstd::string s = "hallo"; // ok std::string s2 = 'hallo'; // nicht ok char c = 'a'; // ok char c2 = "abcd"; // nicht ok
-
Danke

-
SeppJ schrieb:
Was in ' ' steht ist ein Zeichenliteral (Typ const char).
Es gibt keine const PRvalues von skalaren Typen.
#include <cassert> #include <iostream> #include <type_traits> template<class T, class P> bool check_type(P&&) { return std::is_same< T, typename std::remove_reference<P>::type >::value; } int main() { assert(check_type<const char[6]>("Hallo")); if (check_type<const char>('?')) { std::cout << "SeppJ hat recht.\n"; } else { std::cout << "SeppJ hat unrecht.\n"; assert(check_type<char>('?')); } assert(false && "assertions sind wirklich an"); }
-
krümelkacker schrieb:
SeppJ schrieb:
Was in ' ' steht ist ein Zeichenliteral (Typ const char).
Es gibt keine const PRvalues von skalaren Typen.
#include <cassert> #include <iostream> #include <type_traits> template<class T, class P> bool check_type(P&&) { return std::is_same< T, typename std::remove_reference<P>::type >::value; } int main() { assert(check_type<const char[6]>("Hallo")); if (check_type<const char>('?')) { std::cout << "SeppJ hat recht.\n"; } else { std::cout << "SeppJ hat unrecht.\n"; assert(check_type<char>('?')); } assert(false && "assertions sind wirklich an"); }Typen kannste Dir leichter anzeigen lassen. http://ideone.com/5AS7j
-
...wobei es da jetzt noch unterschiede gibt. Mir war es wichtig, dass kein decay stattfindet.
-
krümelkacker schrieb:
...wobei es da jetzt noch unterschiede gibt. Mir war es wichtig, dass kein decay stattfindet.
Was ist ein decay?
-
const char[6] ---[array-to-pointer-decay]--> const char* PRvalue
