What happens if you assign a function to a variable as shown below
unsigned char uchHeaderVer;
uchHeaderVer = GetCodec(Page.Version);
BYTE CWAV::GetCodec(BYTE byVersion)
{
RecorderInfoMap::iterator it;
if ((it = m_mapRecInfo.find(byVersion)) != m_mapRecInfo.end()) {
return (BYTE) ((*it).second.nCodec);
} else {
return 4;
}
}
Version is of type BYTE and is stored in a typedef struct
CodePudding user response:
Every function, if not defined as returning void
, must return a value, the type of returned value is declared at the beginning of function declaration.
int some_func(){
// ^^ This is the type of returned variable.
return 1;
}
What happens in your case is simply assigning the returned value of GetCodec(Page.Version)
to uchHeaderVer
. And if the types uchHeaderVer
and GetCodec(Page.Version)
don't match, a conversion will happen, and if the conversion is not possible, you will get a compile time error.
CodePudding user response:
If the function returns a value and it matches (or can be casted) the variable type, then this value will be assigned to this variable, if not the code will not compile Example :
error: cannot convert ‘std::string {aka std::basic_string}’ to ‘int’ in assignment
If the function returns void
also you will get an error :
error: void value not ignored as it ought to be
CodePudding user response:
What happens if you assign a function to a variable as shown below
You aren't assigning a function to a variable. You are calling a function, and assigning the result to that variable.
You haven't shown what BYTE
is, but it is very likely to be a type alias for either unsigned char
(or possibly char
).
You can't assign a function to a variable, because functions aren't objects. You can only assign pointers to functions to variables, e.g.
BYTE (*pGetCodec)(BYTE) = &CWAV::GetCodec;
auto pGetCodec2 = &CWAV::GetCodec;
using GetCodecF = BYTE (*)(BYTE);
GetCodecF pGetCodec3 = &CWAV::GetCodec;