-
Notifications
You must be signed in to change notification settings - Fork 16
/
const_return_value.cpp
50 lines (40 loc) · 1.04 KB
/
const_return_value.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <vector>
const int f1(){
return 3;
};
const char* f2(){
return "abc";
};
std::vector<int> myvec = {0};
const std::vector<int>& f3(){
return myvec;
}
int main(){
int x = f1();
//error: cannot initialize a variable of type 'char *' with an rvalue of type 'const char *'
//char* s = f2();
const char* s = f2();
//ok
//std::vector<int> v = f3();
//error: binding value of type 'const vector<...>' to reference to type 'vector<...>' drops 'const' qualifier
//std::vector<int>& v = f3();
//ok
const std::vector<int>& v = f3();
std::cout << "int: " << x << std::endl;
std::cout << "const char*: " << s << std::endl;
std::cout << "const vector&: " << v[0] << std::endl;
x = 2;
//error: read-only variable is not assignable
//s[0] = 'd';
std::cout << "int: " << x << std::endl;
//error: cannot assign to return value because function 'operator[]' returns a const value
//v[0] = 1;
return 0;
}
/*
int: 3
const char*: abc
const vector&: 0
int: 2
*/