Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion vlib/v/gen/c/for.v
Original file line number Diff line number Diff line change
Expand Up @@ -917,7 +917,7 @@ fn (mut g Gen) for_in_stmt(node_ ast.ForInStmt) {
g.write('\t${styp} ${c_name(node.val_var)}')
}
if !is_fixed_array {
addr := if node.val_is_mut { '&' } else { '' }
addr := if node.val_is_mut || node.val_is_ref { '&' } else { '' }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve pointer elements during reference iteration

When the fixed array's element type is already a pointer, such as mut items := [2]&Item{} followed by for item in &items, for_in_val_type deliberately leaves the loop variable as &Item rather than creating &&Item. This unconditional & now emits an initializer equivalent to Item *item = &items[idx], whose right side is Item **, so previously valid reference iteration over fixed arrays of pointers fails C compilation. Only take the element address when reference iteration actually added a pointer level.

Useful? React with 👍 / 👎.

if cond_type_is_ptr {
g.writeln(' = ${addr}(*${cond_var})[${idx}];')
} else if cond_is_literal {
Expand Down
1 change: 1 addition & 0 deletions vlib/v/gen/c/testdata/for_in_fixed_array_ref.c.must_have
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
= &(*
3 changes: 3 additions & 0 deletions vlib/v/gen/c/testdata/for_in_fixed_array_ref.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
1
3
5
19 changes: 19 additions & 0 deletions vlib/v/gen/c/testdata/for_in_fixed_array_ref.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
module main

struct Point {
x int
y int
}

struct Holder {
buf [3]Point
}

fn main() {
h := Holder{
buf: [Point{1, 2}, Point{3, 4}, Point{5, 6}]
}
for i in &h.buf {
println(i.x)
}
}