Exact difference between $cast as a task and function

While using $cast in our code, how do we call it as a task or a function precisely?

I did not get it clearly from LRM.

Can anyone give a clear working example of how should it be used as a task/function?

Thanks in advance.

In reply to paragsathe:

When $cast() is used as a task and the casting fails, SV prints a run-time error.
i.e.

$cast(A,B);

When $cast() is used as a function and if casting fails, it returns value “0” and in the case of successful casting, it returns value “1”.
i.e.

if($cast(A,B)) $display("It's a successful casting");
else $display("casting is failed");

In reply to paragsathe:
This terminology originally comes from Verilog where a function call always had a return value and could only be used as part of an expression, and a task call never had a return value and could only be used as a simple statement. Now SystemVerilog allows functions defined with no return value (a void return type), and allows functions with return values to be called as simple statements, and the return value is just thrown away.

So when we say $cast called as a function, we mean it is called as part of an expression

if ($cast(a_handle, b_handle)) something;

and when $cast is called as a task, it is just a simple statement.

$cast(a_handle, b_handle);

The only difference between the two is when the cast fails. Called as a task, it generates a run-time error, which would be consider a testing error.

When called as a function, it never generates an error, it just returns 1 for success and 0 for unsuccessful. You would use a $cast as a function when you have a class handle and want to know what the type of the class object is. Normally, you have a base class variable and want to try casting it to an extended class variable type.

In reply to bdreku:

Means whenever we use it in an assignment or expression, it will be used as a function.

if($cast (A,B)
$display(“It’s a successful casting”);
bit a;
a = $cast (A,B);

While when we use it as a standalone statement it will be used as a task.

$cast(A,B);

Thanks a lot for the reply. I was thinking in the same direction but was a bit confused regarding the exact implication of a $cast as a function/task.

Thanks bdreku and Dave. You cleared the dust over my concept very clearly :)