rahul gupta
rahul gupta

Reputation: 11

difference between char and const char

 # include <iostream>
# include <string.h>
using namespace std;
int main()
{
    int a=10;
    int b=20;
    char op[10];
    const char p='+';
    cout<<"enter the operation"<<endl;
    cin>>op;
    if(!strcmp(op,p)==0)
{
        cout<<a+b;
}
    return 0;
}

compilation result

12 17 C:\Users\DELL\Documents\cac.cpp [Error] invalid conversion from 'char' to 'const char*' [-fpermissive]

I am a beginner. Please tell me what mistake have I done.

Upvotes: 0

Views: 959

Answers (2)

Raindrop7
Raindrop7

Reputation: 3911

there is no version of strcmp that takes a single character as a parameter but instead it takes two string and compares them.

if you want to compare a single char variable with a string you can compare it with the first element of string or with any other element:

#include <iostream>
#include <string>


int main()
{

    char op[10]  = "Hi";
    const char p = '+';

   // if( strcmp( op, p) ) // error cannot covert parameter 2 from char to const char*
   //    cout << "op and p are identic" << std::endl;
   // else
   //    std::cout << "op and b are not identic" << std::endl;

    if(op[0] == p)
        std::cout << "op[0] and p are identic" << std::endl;
    else
        std::cout << "op[0] and p are not identic" << std::endl;

    const char* const pStr  = "Bye"; //constant pointer to constant character string: pStr cannot change neither the address nor the value in address
    const char* const pStr2 = "bye"; // the same as above

    // pStr++; //error
    // pStr[0]++; // error 


    if( !strcmp( pStr, pStr2) )
        std::cout << "pStr and pStr2 are identic" << std::endl;
    else
        std::cout << "pStr and pStr2 are Not identic" << std::endl;

    return 0;
}

Upvotes: 0

Topological Sort
Topological Sort

Reputation: 2890

This isn't about the difference between char and const char, but between char [] and char.

strcmp expects two character arrays.

op is an array of (10) characters. Good: that's what strcmp expects.

p is a single character. Not good: strcmp needs a char array, and p isn't any kind of array, but a single character.

You can change p from a single char '+' to a char array "+", or compare only the 0th character of op, as suggested in a comment above.

Upvotes: 2

Related Questions