Sunday, November 30, 2008

Verilog Gotcha 02

Dear Readers,

Most of us have gotten used to the idea that numerical operands in an expression are size-extended to the size of the widest operand. We are less used to it with respect to strings, and it can hit us when we least expect it.

One particular case where it is easy to forget size-extension is in the conditional operator. If we write

cond ? expr1 : expr2

then the shorter expression of expr1 and expr2 is extended to the size of the wider one. But suppose we have something like this:

integer file; file = $fopen({"filename", dat1 ? ".dat1" : ".dat"}) ;

In this contrived example, we concatenate a file extension .dat1 or .dat to the given filename, where a variable called dat1 tells us the type of the file. If the variable dat1 is true, there is no problem, we open a file named ―filename.dat1, but if dat1 is false, then we try to open a file called ―filename .dat, with a space before ―.dat, which is extended to the size of ―.dat before being concatenated to ―filename. GOTCHA!

Actually, the shorter string literal is not extended with a space character, which is x20 ASCII, but rather with zeroes (zero-extension), which are null characters.

However, when used as a string, this often becomes a space. Note that if we had assigned the concatenation to a variable of string type, this would not occur.

string temp;
temp = {"filename", dat1 ? ".dat1" : ".dat"} ;
file = $fopen(temp) ;

The shorter string literal would still be zero-extended. However, upon assignment to string variables, null-characters are ignored, so ―.dat would still be appended directly to ―filename.

No comments: