Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a single character to a function in C++

Tags:

c++

function

I've searched through the net for my problem and I know that for returning array values from a function to our main function(or any other functions, anyway) I need to use pointers(it can be done in various methods), and I can use them for solving my issue either, however, I'm still curious about why my program behaves in an unanticipated(to me of course!) way, I'm a beginner so please explain in as much detail as you can, here's my tiny program:

char Calc(char);

int main(){
    Calc('1');
    return 0;
}

char Calc(char a) {
    a = int(a);
    std::cout << a <<std::endl;
    std::cout << int('1');
    _getch();
    return 'c';
}

According to ASCII table, the integer of '1' is 49, so both commands in my Func function have to display the same thing, namely 49, but it displays this as the output:

1
49

What am I missing here? Thanks.

like image 581
M-J Avatar asked Apr 18 '26 18:04

M-J


1 Answers

std::cout << a <<std::endl;

displays 1 since std::basic_ostream& operator<< is overloaded for chars as a non-member operator and displays their corresponding ASCII values. On the other hand,

std::cout << int('1') <<std::endl;

displays the char '1' as an int (due to the explicit cast), so you see the corresponding ASCII index of 49 instead. That's because for arithmetic types the member std::basic_ostream& operator<< is being picked up instead.

Note that your line

a = int(a);

doesn't do anything, it doesn't change the type of a to int; it just casts the RHS to int then assigns back the int to the original char (with no loss of data obviously). In C or C++ the type is set in stone at compile time.

like image 123
vsoftco Avatar answered Apr 21 '26 07:04

vsoftco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!