how to explain this sum behavior in verilog ?

Status
Not open for further replies.

zhangljz

Member level 5
Joined
Oct 19, 2013
Messages
81
Helped
1
Reputation
2
Reaction score
1
Trophy points
8
Activity points
648
Hello everyone,

I have a question about the sum operation in verilog in modelsim. Here is the code:

Code Verilog - [expand]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
reg  sign;
  reg [1:0] delta;
  wire [1:0] sum_1, sum_2;
  wire [1:0] sign_x;
  
  initial begin
    sign =0;
    delta = 1;
  end
  
  assign sum_1 = delta + sign?3:0;
  
  assign sign_x = sign?3:0;
  assign sum_2 = delta + sign_x;



The simulation shows sum_1 is 3, sum_2 is 1 which is what we expect.

I can not figure out why they have different behavior

Somebody can help ?

Thank you
 

See Table 11-2—Operator precedence and associativity in the IEEE 1800-2012 LRM
 

Hi dave_59,

Thank you. I see why

It should be:
assign sum_1 = delta + (sign?3:0);
 

As a general rule I use parenthesis to enforce the correct precedence, regardless if it may be redundant. Saves you from having to debug gotchas like you observed.

e.g. if ( ((a == b) && (c == d)) || f )
instead of: if ( a==b && c==d || f )
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…