? Operator

This results in an error, invalid conversion from const char* to char*. I didn't declare any variable as const, so why does this happen?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;
int main()
{
   cout << "Enter number\n";
   int num;
   cin >> num;
   cout << "Enter another number\n";
   int another;
   cin >> another;
   char* pch = num>another ?  "first bigger\n" :  "second bigger\n";
   cout << pch;
   return 0;
}
there is another easy way to do that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <iostream>
using namespace std;
int main()
{
   cout << "Enter number\n";
   int num;
   cin >> num;
   cout << "Enter another number\n";
   int another;
   cin >> another;
  num>another ?  cout<<"first bigger\n" : cout<< "second bigger\n";
  
  system ("pause");
   return 0;
}
So why doesn't cout-ing the pointer to char work if the strings represent the memory addresses of the first char in the strings?
 
    const char* pch = num>another ?  "first bigger\n" :  "second bigger\n";

The two literals are constant, you are not allowed to modify them during program execution. Declare the pointer as const.

Yet another alternative, using parentheses around the expression:
 
    cout << (num>another ? "first" : "second") << " bigger\n";
Topic archived. No new replies allowed.