I think I am missing smth back in my theoretical background on this thing. I know there were similar posts but I still do not get it.
I have such a code:
void somefunc1(Word &Key)
{
somefunc2(Key);
}
void somefunc2(char &char1)
{
return;
}
compiler generates me an error here:
somefunc2(Key);
[BCC32 Error] Unit1.cpp(830): E2357 Reference initialized with 'unsigned short', needs lvalue of type 'char'
I found out that it is because of the ANSI 2003 regulation on C++ dealing with temporaries and references but I still do not get what is wrong here.
when I do c-style conversion:
somefunc2( *(char*)&Key )
it resolves an issue.
Can anyone hint me what is wrong and why is it wrong?
WORD &Key;
A reference is always an alias for some other object, and it must be initialized with an object that already exists. Thus, the above declaration is not valid. The following is instead correct:
WORD &Key = alreadyExistingKey;
[The above is not relevant anymore, the question has changed.]
EDIT:
void somefunc1(Word &Key)
{
somefunc2(Key);
}
void somefunc2(char &char1)
{
return;
}
[BCC32 Error] Unit1.cpp(830): E2357 Reference initialized with 'unsigned short', needs lvalue of type 'char'
The compiler is telling you that somefunc2
is expecting [a reference, that is, an alias for] a char
. But Key
in somefunc1
is instead a Word
, which I understand to be a typedef for unsigned short
.
It seems to me that your "c-style" remedy is brutally reinterpreting &Key
, which is the address of an unsigned short
, as the address of a char
. What you are passing to somefunc2
is therefore the first byte of Key
, interpreted as a (signed) char
. I guess that the result depends on endianness. I wouldn't rely on that code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With