Strings: C vs. C++
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1// Vorlesung: 17.3.2023
2#include <cassert> // assert()
3#include <cstring> // strlen(c-string) from string.h
4#include <iostream>
5#include <string>
6using namespace std;
7
8int main()
9{
10 // C++
11 string hpp("Hello"); // (potentially) flexible C++-string
12 size_t spp = hpp.size();
13 size_t lpp = hpp.length();
14 assert(spp==lpp); // size==length for C++-string
15 cout << "c++ :"<< hpp << ": lang " << lpp << " " << spp << endl;
16
17 // simple hack C++
18 string const sdummy("yUMMMY");
19 hpp[lpp] = 'x'; // no compiler warning; but incorrect index
20 cout << "c++2:"<< hpp << ": lang " << lpp << " " << spp << endl;
21 cout << sdummy << endl; // const string remains unchanged
22
23 // C
24 char hcc[] = "Hello"; // fixed size C-string
25 size_t lcc = strlen(hcc);
26 int scc = sizeof(hcc)/sizeof(char);
27
28 cout << "C :"<< hcc << ": lang " << lcc << " " << scc << endl;
29
30 // simple hack C:
31 char const cdummy[] = "Yummy";
32 cout << cdummy << endl; // the compiler won't allocate cdummy without using
33 hcc[lcc] = 'X'; // no compiler warning; correct index - but overrides the '\0'
34 // Suddenly, more charachters of hcc are printed than available
35 size_t lcc2 = strlen(hcc); // len() searches for the first '\0'
36 int scc2 = sizeof(hcc)/sizeof(char); // uses static info from declaration
37 cout << "C 2 :"<< hcc << ": lang " << lcc2 << " " << scc2 << endl;
38
39 return 0;
40}
int main()
Definition main.cpp:8