GAT higher-ranked implied static

Prompt:
Assume stable Rust 1.85.0, edition 2021. Does the following program compile? Give the decisive lifetime diagnosis, including what the higher-ranked bound implies for `data`.
```rust
use std::fmt::Debug;
trait L { type Item<'a> where Self:'a; fn next<'a>(&'a mut self)->Option<Self::Item<'a>>; }
struct W<'x>{ s:&'x mut [i32] }
impl<'x> L for W<'x>{ type Item<'a>=&'a mut [i32] where Self:'a; fn next<'a>(&'a mut self)->Option<Self::Item<'a>>{None} }
fn all<I:L>(mut x:I) where for<'a> I::Item<'a>:Debug { while let Some(v)=x.next(){println!("{v:?}")} }
fn main(){let mut data=[1,2]; all(W{s:&mut data});}
```

System: You are a Rust language-semantics expert. Answer only under the stated toolchain and explain the decisive rule.

compilation_conclusion: Correct compilation result under Rust 1.85.0.
  0 — Says the program compiles, or gives no definite conclusion.
  1 — Says it fails to compile because the higher-ranked associated-type bound effectively requires the borrow backing `W` to be valid for `'static` under the current borrow checker's implied-`'static` limitation.

lifetime_reasoning: Explains the quantification and its consequence.
  0 — Attributes failure to `Debug`, the loop, or ordinary mutable aliasing without explaining the universal lifetime requirement.
  1 — Explains that `for<'a> I::Item<'a>: Debug` must hold for every `'a`; with this GAT pattern the compiler infers an effectively `'static` requirement, but local `data` cannot be borrowed for `'static`.


Underscore pattern and drop timing

Prompt:
Assume stable Rust 1.85.0, edition 2021. What exact text is printed?
```rust
struct P(&'static str);
impl Drop for P { fn drop(&mut self){ print!("{}",self.0); } }
fn main(){
 let x=P("x");
 let y=P("y");
 let _=x;
 print!("A");
 drop(y);
 print!("B");
}
```
Explain whether `let _ = x` moves or drops `x`, and when each destructor runs.

System: You are a Rust language-semantics expert. Give the exact output and decisive reasoning.

exact_output: The exact character sequence.
  0 — Gives any output other than `AyBx`.
  1 — Gives exactly `AyBx`.

drop_semantics: Correctly accounts for the wildcard pattern and scopes.
  0 — Claims `let _ = x` moves or immediately drops `x`, or otherwise gives destructor timing inconsistent with the output.
  1 — States that a wildcard pattern does not bind or move `x`; `y` is explicitly dropped after `A`, then `B` prints, and `x` drops at the end of `main`.


Autoref method resolution to double reference

Prompt:
Assume stable Rust 1.85.0. Does this compile? If so, explain the receiver adjustment that makes the implementation applicable.
```rust
trait T { fn f(self); }
impl T for &&i32 { fn f(self) {} }
fn main(){ let x=0; (&x).f(); }
```

System: Apply Rust method-call receiver candidate construction precisely.

resolution_result: Compilation result and selected implementation.
  0 — Says no method applies to receiver `&i32`.
  1 — States that the program compiles and selects the `T for &&i32` implementation.

candidate_reasoning: Required implicit receiver adjustment.
  0 — Claims the compiler dereferences `&x` to `i32` and calls the same implementation without borrowing.
  1 — Explains that method-call candidate construction includes an autoref of the receiver: the expression of type `&i32` can be borrowed as `&&i32`, matching the implementation's by-value `self` type.


Move closure capture and outer copy

Prompt:
Assume stable Rust 1.85.0. What exact text is printed, and why is the closure callable twice?
```rust
fn main(){
 let mut n=0;
 let mut c=move || { n+=1; print!("{n}"); };
 c(); c();
 print!("-{n}");
}
```

System: Give exact output and closure-trait/capture reasoning.

exact_output: Exact standard output.
  0 — Gives anything other than `12-0`.
  1 — Gives exactly `12-0`.

capture_and_trait: Explains the independent captured state.
  0 — Claims the outer `n` becomes 2, or that the closure is `FnOnce` merely because it is `move`.
  1 — Explains that `i32` is copied into the move closure, mutation makes the closure `FnMut`, and each call mutates the captured copy while outer `n` remains 0.


Two-phase borrow in method arguments

Prompt:
Assume stable Rust 1.85.0. Is this program accepted? Explain the interaction between two-phase borrowing and argument evaluation.
```rust
fn main(){
 let mut v=vec![10,20];
 v.push(v.len());
 println!("{v:?}");
}
```

System: Answer under stable Rust and distinguish reservation from activation.

result: Compilation and output.
  0 — Says borrow checking rejects it or gives output other than `[10, 20, 2]`.
  1 — States that it compiles and prints `[10, 20, 2]`.

two_phase_reasoning: Explains why the immutable length read is permitted.
  0 — Says mutable and immutable borrows freely overlap in general or omits the ordering mechanism.
  1 — Explains that the implicit mutable receiver borrow is reserved before argument evaluation and activated for the call only after `v.len()` has completed, so the shared borrow occurs during the reservation phase.


Overlapping conditional blanket impls

Prompt:
Assume stable Rust 1.85.0. Does this compile? Give the precise coherence reason.
```rust
trait X {}
impl<T> X for T where T: Iterator {}
impl<T> X for T where T: IntoIterator {}
fn main(){}
```

System: Analyze Rust coherence, including possible types rather than currently named standard types.

coherence_result: Whether the impl set is accepted.
  0 — Says it compiles because `Iterator` and `IntoIterator` are different traits.
  1 — States that the two blanket implementations conflict and the crate is rejected.

overlap_reasoning: Explains existential overlap.
  0 — Bases the answer only on whether a particular current standard-library type implements both traits.
  1 — Explains that some type may satisfy both bounds (and iterator types commonly can), making both impls applicable to the same `T`; where-clauses do not make these impls disjoint.


ManuallyDrop inside array

Prompt:
Assume stable Rust 1.85.0. What exact output is guaranteed?
```rust
use std::mem::ManuallyDrop;
struct D(u8);
impl Drop for D { fn drop(&mut self){print!("{}",self.0)} }
fn main(){
 let mut a=[ManuallyDrop::new(D(1)),ManuallyDrop::new(D(2))];
 unsafe { ManuallyDrop::drop(&mut a[0]); }
 print!("X");
}
```
Account for every destructor.

System: Give exact output and distinguish dropping the wrapper from its payload.

exact_output: Exact destructor and print sequence.
  0 — Gives anything other than `1X`.
  1 — Gives exactly `1X`.

destructor_accounting: Why the second payload is not dropped.
  0 — Claims array scope exit automatically drops `D(2)` or double-drops `D(1)`.
  1 — Explains that the explicit unsafe call drops only the first payload; `ManuallyDrop<T>` suppresses automatic destruction of both wrapped payloads at array scope exit, so `D(2)` leaks.


Invalid bool representation

Prompt:
Assume stable Rust 1.85.0. Is the marked unsafe read defined under Rust's validity requirements?
```rust
fn main(){
 let b: bool = unsafe { std::mem::transmute::<u8,bool>(2) };
 println!("{b}"); // marked use
}
```
Do not predict a particular optimized output; classify the program and identify the violated invariant.

System: Classify unsafe-code validity precisely; do not treat observed output as specification.

validity_classification: Correct semantic classification.
  0 — Calls it defined, implementation-defined, or merely unspecified.
  1 — Classifies constructing/using the invalid `bool` value as undefined behavior; no output is guaranteed.

invariant: Names the invalid representation.
  0 — Claims every nonzero byte is a valid Rust `bool` representation.
  1 — States that a valid Rust `bool` must have a valid bit pattern corresponding to false or true (0 or 1); byte value 2 violates the type's validity invariant.


Supertrait method disambiguation

Prompt:
Assume stable Rust 1.85.0. What exact output does this produce?
```rust
trait A { fn f(&self){print!("A")} }
trait B: A { fn f(&self){print!("B")} }
struct S;
impl A for S {}
impl B for S {}
fn main(){
 let x:&dyn B=&S;
 B::f(x);
 A::f(x);
}
```

System: Apply trait-object coercion and fully qualified trait calls.

exact_output: Exact text or compilation diagnosis.
  0 — Says it fails or gives output other than `BA`.
  1 — States that it compiles and prints exactly `BA`.

dispatch_reasoning: Explains the two explicitly selected defaults.
  0 — Treats the same-named supertrait method as an override or says `B::f` dynamically replaces `A::f`.
  1 — Explains that the fully qualified calls select distinct trait methods: `B::f` prints `B`; `&dyn B` supports its `A` supertrait method and `A::f` prints `A`.


Sized generic method on trait object

Prompt:
Assume stable Rust 1.85.0. Does this compile? Explain object safety/dyn compatibility at the coercion.
```rust
trait Q {
 fn make<T>(&self, x:T) where Self:Sized;
 fn n(&self)->i32 {3}
}
struct S;
impl Q for S { fn make<T>(&self,_:T){} }
fn main(){ let q:&dyn Q=&S; println!("{}",q.n()); }
```

System: Analyze dyn compatibility method by method.

compilation_and_output: Correct result.
  0 — Says the generic method makes the trait non-dyn-compatible, or gives output other than `3`.
  1 — States that it compiles and prints `3`.

dyn_reasoning: Effect of the `Self: Sized` restriction.
  0 — Claims generic methods are always callable through trait objects.
  1 — Explains that the generic `make` is excluded from the trait object's callable interface by `where Self: Sized`, so it does not prevent `Q` from being used as `dyn Q`; `n` remains callable.


Select operand evaluation

Prompt:
Assume Go 1.23. What exact text is printed? Explain expression evaluation on entry to `select` and why the selected case wins.
```go
package main
import "fmt"
func ch(s string,c chan int) chan int { fmt.Print(s); return c }
func val(s string) int { fmt.Print(s); return 7 }
func main(){
 var nilc chan int; c:=make(chan int); close(c)
 select{
 case ch("A",nilc)<-val("a"): fmt.Print("X")
 case v:=<-ch("B",c): fmt.Print("Y",v)
 default: fmt.Print("D")
 }
}
```

System: Apply the Go 1.23 specification and give exact output.

exact_output: Exact emitted text.
  0 — Gives anything other than `AaBY0`.
  1 — Gives exactly `AaBY0`.

select_reasoning: Evaluation and selection rules.
  0 — Says only the chosen case operands are evaluated, or that default runs.
  1 — Explains that channel operands and send RHS expressions for all cases are evaluated once in source order (`A`, `a`, `B`); the nil-channel send cannot proceed, receiving from the closed channel can proceed immediately and yields zero, so that case prints `Y0`.


Typed nil inside interface

Prompt:
Assume Go 1.23. Does this program panic, and what exact line is printed before termination?
```go
package main
import "fmt"
type E struct{}
func (*E) Error() string { return "e" }
func f() error { var p *E=nil; return p }
func main(){ e:=f(); fmt.Printf("%t %T\n",e==nil,e); fmt.Println(e.Error()) }
```

System: Distinguish a nil interface from an interface containing a typed nil pointer.

observable_result: Printed line and panic status.
  0 — Says `e == nil`, gives a different first line, or says no panic occurs.
  1 — States the first line is `false *main.E`, then the call panics due to dereferencing the nil `*E` receiver while evaluating `return "e"`?
  2 — States the first line is `false *main.E` and, crucially, that no panic occurs: `Error` does not dereference its nil receiver and prints `e` on the next line.

interface_reasoning: Dynamic type/value explanation.
  0 — Treats the interface as nil because its dynamic pointer value is nil.
  1 — Explains that the interface has dynamic type `*main.E` and dynamic value nil, so the interface itself is non-nil; invoking a method with a nil pointer receiver is allowed unless its body dereferences the receiver.


Range slice header snapshot

Prompt:
Assume Go 1.23. What exact text is printed?
```go
package main
import "fmt"
func main(){
 s:=[]int{1,2,3}
 for i,v:=range s {
  fmt.Print(i,v,";")
  if i==0 { s=append(s,4,5); s[1]=9 }
 }
 fmt.Print("|",s)
}
```
Explain which length and backing values the range loop observes.

System: Give exact output under the language specification.

exact_output: Exact output including separators.
  0 — Gives anything other than `01;12;23;|[1 9 3 4 5]`.
  1 — Gives exactly `01;12;23;|[1 9 3 4 5]`.

range_reasoning: Why the mutation is not seen by loop values.
  0 — Claims the loop grows to five iterations or must print 9 for index 1.
  1 — Explains that the range expression's slice header/length is fixed before iteration; the append reallocates because the original literal has capacity 3, so the loop continues over the old three-element backing array while `s` names the new array.


Generic operator over type set

Prompt:
Assume Go 1.23. Does this generic function compile? Give the precise reason.
```go
package p
type N interface{ ~int | ~string }
func F[T N](a,b T) T { return a+b }
```

System: Apply operator validity across every type in the constraint's type set.

compilation: Whether `+` is permitted for all types in the type set.
  0 — Says it is rejected because int addition and string concatenation are different operations.
  1 — States that it compiles.

type_set_reasoning: Common operation and result type.
  0 — Claims a type switch or conversion is required.
  1 — Explains that every type in the set supports binary `+` on two operands of that same type and produces that type; the operation need not have identical machine semantics across all members.


Named result, return, and defer arguments

Prompt:
Assume Go 1.23. What exact text is printed?
```go
package main
import "fmt"
func f() (r int) {
 defer func(x int){ fmt.Print(x,r); r++ }(r)
 r=5
 return 7
}
func main(){fmt.Print("|",f())}
```

System: Track defer argument evaluation and named-result assignment exactly.

exact_output: Exact output order.
  0 — Gives anything other than `07|8`.
  1 — Gives exactly `07|8`.

defer_reasoning: Distinguishes argument capture from closure access.
  0 — Says deferred argument `x` is evaluated at function return or misses the final increment.
  1 — Explains that `x` captures initial `r=0` when defer is registered; the return expression assigns 7 to named `r`; defer prints `0` and `7`, increments `r` to 8, and only then does `main` print `|8`.


Close-receive happens-before

Prompt:
Assume Go 1.23. Is the final value of `x` guaranteed to be 1, guaranteed to be 2, or not constrained to either? Explain using channel close synchronization.
```go
package main
var x int
func main(){
 c:=make(chan struct{})
 go func(){ x=1; close(c) }()
 <-c
 x=2
 println(x)
}
```

System: Use the Go memory model, not scheduling intuition.

value: Guaranteed printed integer.
  0 — Says 1, unconstrained, or race-dependent.
  1 — States it is guaranteed to print 2.

memory_order: Happens-before chain and race status.
  0 — Claims the read/write of `x` race or that close provides no synchronization.
  1 — Explains that closing `c` is synchronized before the receive that observes closure; therefore the goroutine's `x=1` happens before the receive, and the sequenced later `x=2` happens before `println`, with no conflicting unordered access.


Map elements and method sets

Prompt:
Assume Go 1.23. What exact text is printed?
```go
package main
import "fmt"
type I interface{ M() }
type S struct{ n int }
func (s S) M(){fmt.Print("V",s.n)}
func (s *S) P(){fmt.Print("P",s.n)}
func main(){
 m:=map[int]S{0:{3}}
 m[0].M()
 var i I=m[0]; i.M()
}
```

System: Analyze addressability and value-receiver method sets.

result: Compilation and output.
  0 — Says map elements cannot be used for any method call, or gives output other than `V3V3`.
  1 — States that it compiles and prints `V3V3`.

method_set_reasoning: Why `M` works despite non-addressability.
  0 — Relies on implicit addressing of `m[0]`.
  1 — Explains that `S` itself has the value-receiver method `M`, so neither call needs the non-addressable map element to be implicitly addressed; `S` also implements `I`. A call to pointer-receiver `P` on `m[0]` would fail.


Buffered send synchronization

Prompt:
Assume Go 1.23 and that `GOMAXPROCS` may be any positive value. Is this program data-race-free? Is it guaranteed to print `1`?
```go
package main
var x int
func main(){
 done:=make(chan bool,1)
 go func(){ x=1; done<-true }()
 <-done
 println(x)
}
```

System: Use the formal channel synchronization rule.

conclusion: Race freedom and value.
  0 — Calls it racy or says the print may be 0.
  1 — States that it is data-race-free and guaranteed to print 1.

happens_before: Correct synchronization edge for the buffered channel.
  0 — Claims buffered sends never synchronize until the buffer is reused.
  1 — Explains that a send on a channel is synchronized before completion of the corresponding receive, even when buffered; program order places `x=1` before the send and the read after the receive.


Overlapping append within slice

Prompt:
Assume Go 1.23. What exact text is printed?
```go
package main
import "fmt"
func main(){
 a:=[]int{1,2,3}
 b:=append(a[:1],a[2:]...)
 fmt.Print(a,"|",b)
}
```
Account for overlapping source and destination and the shared backing array.

System: Apply append's overlap behavior and capacity rules.

exact_output: Exact slice values.
  0 — Gives anything other than `[1 3 3]|[1 3]`.
  1 — Gives exactly `[1 3 3]|[1 3]`.

backing_array_reasoning: Why mutation occurs in place.
  0 — Claims overlap is undefined or that allocation is required.
  1 — Explains that `a[:1]` has sufficient capacity, append may reuse the same backing array, and appending the overlapping `a[2:]` is defined like copying; element 3 is written into index 1, leaving index 2 unchanged.


Constraint-only comparable interface

Prompt:
Assume Go 1.23. Does this declaration compile? Explain why `comparable` does or does not satisfy the ordinary interface use.
```go
package p
var x interface{ comparable }
```

System: Distinguish basic interfaces from constraint-only non-basic interfaces.

compilation: Use outside a type constraint.
  0 — Says it declares an interface value accepting all comparable dynamic values.
  1 — States that it does not compile because `interface{ comparable }` may only be used as a type constraint, not as the type of an ordinary variable.

interface_reasoning: Nature of the interface.
  0 — Confuses the predeclared constraint with the empty interface or runtime comparability checks.
  1 — Explains that embedding `comparable` creates a non-basic interface representing a type set for constraints; it is not an ordinary runtime interface type.


C17 release sequence through relaxed RMW

Prompt:
Assume ISO C17. `data` and `flag` are initialized to zero before three threads begin. B's successful compare-exchange reads A's `1`, and C's terminating acquire load reads B's `2`.
```c
#include <stdatomic.h>
atomic_int data,flag;
void A(void){atomic_store_explicit(&data,1,memory_order_relaxed);atomic_store_explicit(&flag,1,memory_order_release);}
void B(void){int e=1;while(!atomic_compare_exchange_weak_explicit(&flag,&e,2,memory_order_relaxed,memory_order_relaxed))e=1;}
int C(void){while(atomic_load_explicit(&flag,memory_order_acquire)!=2){} return atomic_load_explicit(&data,memory_order_relaxed);}
```
May C return 0? Then answer again if B's successful RMW is replaced by a relaxed store of 2 that C reads. Distinguish forbidden from not guaranteed.

System: Give a formal C17 memory-model argument.

two_conclusions: Correct result for RMW and store variants.
  0 — Gets both variants wrong or gives no distinction.
  1 — Correctly says the RMW variant forbids 0, but does not correctly classify the store variant.
  2 — Says the RMW variant cannot return 0; with B's relaxed store, 1 is not guaranteed and C may return 0.

memory_model_proof: Release-sequence and synchronization reasoning.
  0 — Claims a relaxed operation itself is acquire/release or relies only on coherence.
  1 — Explains that B's RMW is in the release sequence headed by A's release store, so C's acquire reading 2 synchronizes with A and sees prior `data=1`; a later relaxed plain store by another thread is not in that release sequence, so no such happens-before edge exists.


Object representation copied twice

Prompt:
Assume ISO C17 and a conforming hosted implementation where `unsigned char` has no padding bits. Is this function defined for every `float x`? If defined, what semantic property does it test?
```c
#include <string.h>
int f(float x){ unsigned char a[sizeof x],b[sizeof x]; memcpy(a,&x,sizeof x); memcpy(b,&x,sizeof x); return memcmp(a,b,sizeof x)==0; }
```

System: Separate value semantics, padding, and indeterminate representations.

classification: Whether the operations are defined.
  0 — Calls it undefined merely because `float` may contain padding or NaNs.
  1 — States it is defined and always returns 1 for the two copies taken from the same unchanged object.

representation_reasoning: What `memcpy` and `memcmp` compare.
  0 — Claims it compares floating-point numerical equality.
  1 — Explains that character arrays may inspect object representations; both arrays receive the same bytes, including any padding representation copied from the same object, so bytewise comparison is equal. It is not a general numerical-equality test between two floats.


Effective type versus common initial sequence

Prompt:
Assume ISO C17. Classify the marked access.
```c
#include <stdlib.h>
struct A{int x;}; struct B{int x;};
int main(void){
 void *p=malloc(sizeof(struct A));
 ((struct A*)p)->x=42;
 int y=((struct B*)p)->x; /* marked */
 free(p); return y;
}
```
Is common initial sequence relevant?

System: Apply C17 effective-type and union common-initial-sequence rules.

classification: Definedness of the lvalue access.
  0 — Calls the read defined because both structs begin with `int x`.
  1 — Classifies the read through `struct B *` as undefined behavior.

alias_reasoning: Effective type and inapplicable exception.
  0 — Invokes the common-initial-sequence permission outside a union.
  1 — Explains that the store through `struct A *` gives allocated storage effective type `struct A`; accessing it as incompatible `struct B` violates the effective-type aliasing rule, and the common-initial-sequence rule applies to union members, not arbitrary separately declared structs.


Unsequenced scalar modifications

Prompt:
Assume ISO C17. Is the result of `f(5)` defined, unspecified, implementation-defined, or undefined?
```c
int f(int i){ return i++ + i++; }
```
Do not give a numeric result unless the standard guarantees one.

System: Use C17 sequencing terminology precisely.

classification: Correct standard category.
  0 — Calls the result 11, 12, unspecified, or implementation-defined.
  1 — Classifies the expression as undefined behavior.

sequencing_reason: The conflicting evaluations.
  0 — Attributes it merely to unspecified operand evaluation order.
  1 — States that the two side effects modifying `i` are unsequenced relative to each other within the full expression; unsequenced modifications of the same scalar object cause undefined behavior.


Unsequenced pointer increments

Prompt:
Assume ISO C17. What does `g()` return?
```c
int g(void){
 int a[3]={10,20,30};
 int *p=&a[0];
 return *p++ + *p++;
}
```
Classify the expression before attempting arithmetic.

System: Do not infer an execution order where the standard supplies none.

classification: Whether a return value is defined.
  0 — Gives 30, 40, or any fixed value.
  1 — States that behavior is undefined, so no return value is guaranteed.

reason: Why distinct pointees do not save it.
  0 — Says it is safe because the dereferences can refer to different array elements.
  1 — Explains that both operands unsequencedly modify the same scalar object `p`; the rule concerns `p`, regardless of which array elements the dereferences might reach.


Byte buffer cast to uint32_t

Prompt:
Assume ISO C17, `CHAR_BIT==8`, and `uint32_t` exists. Is `h` strictly defined on every implementation satisfying those assumptions?
```c
#include <stdint.h>
uint32_t h(unsigned char *p){ return *(uint32_t*)p; }
```
The caller guarantees only that `p` points to the first element of an array of four `unsigned char` objects containing initialized bytes.

System: Account separately for alignment and effective type.

classification: Portability and UB.
  0 — Calls it strictly defined because character arrays may alias any type.
  1 — States it is not strictly defined and may have undefined behavior.

two_hazards: Required independent reasons.
  0 — Mentions only endianness or value differences.
  1 — Identifies at least one of insufficient alignment or accessing `unsigned char` array objects through an incompatible `uint32_t` lvalue.
  2 — Identifies both potential misalignment and effective-type/incompatible-lvalue access; endianness would affect value only after those validity issues were avoided.


String literal exactly fills character array

Prompt:
Assume ISO C17. Is this initializer a constraint violation, and if accepted what is `sizeof s`?
```c
char s[3] = "abc";
```

System: Distinguish ordinary string storage from the character-array initialization exception.

answer: Validity and size.
  0 — Says it is invalid because no null terminator fits, or gives a size other than 3.
  1 — States it is valid and `sizeof s` is 3.

initialization_rule: Terminator omission exception.
  0 — Claims the array nevertheless contains four bytes or an implicit terminator out of bounds.
  1 — Explains that when an array of character type is initialized by a string literal, successive characters including the terminating null initialize the array only if there is room or the array size is unknown; here the three non-null characters fit and the terminator is omitted.


One-past pointer equality across objects

Prompt:
Assume ISO C17. Is `p == q` guaranteed true, guaranteed false, or unspecified after these declarations?
```c
int a[1], b[1];
int *p = a + 1;
int *q = b;
```
Assume the implementation may place the arrays adjacently.

System: Apply pointer equality rules, not relational comparison rules.

classification: Allowed equality result.
  0 — Says it is guaranteed false solely because the pointers derive from different arrays, or guaranteed true.
  1 — States that the comparison can be true if the one-past address of `a` equals the address of `b`, and otherwise false; placement is implementation-dependent, so the given facts do not guarantee either result.

equality_reasoning: Distinguishes pointer equality from provenance folklore.
  0 — Calls the comparison itself undefined.
  1 — Explains that equality comparison of these pointers is defined; a pointer one past one array may compare equal to a pointer to a different object located immediately after it.


Dereferencing malloc zero result

Prompt:
Assume ISO C17. Does this function have defined behavior for `n==0`?
```c
#include <stdlib.h>
void f(size_t n){ int *p=malloc(n*sizeof *p); if(!p) return; p[0]=1; free(p); }
```
Account for every permitted result of `malloc(0)`.

System: Quantify over all conforming `malloc(0)` behaviors.

classification: Definedness at zero size.
  0 — Calls it always safe because the null check succeeds or returns.
  1 — States that it is not guaranteed defined: `malloc(0)` may return a non-null pointer that cannot be used to access an object, and `p[0]=1` then has undefined behavior.

malloc_zero_cases: Both allowed outcomes.
  0 — Claims `malloc(0)` must return null.
  1 — Explains that `malloc(0)` may return null, in which case the function returns, or a unique/non-null pointer value that may be passed to `free` but does not provide storage for an `int`; the null test does not establish dereferenceability.


Flexible array member sizeof

Prompt:
Assume ISO C17 and `sizeof(int)==4`. What is the value of `sizeof(struct S)`?
```c
struct S { char c; int a[]; };
```
Is 8 the only conforming answer? Explain the flexible-array sizing rule and trailing padding.

System: Do not assume a particular ABI beyond the stated integer size.

portability_conclusion: Whether one numeric size follows.
  0 — States that the standard guarantees 8.
  1 — States that the standard does not determine a unique numeric size from `sizeof(int)==4`; 8 is possible but not the only conforming answer.

layout_reasoning: Rule for flexible member omission and padding.
  0 — Counts one actual `int` element in the flexible member.
  1 — Explains that the flexible array member contributes no elements to `sizeof`; the structure may have padding and its size is as if the flexible member were omitted except for permitted trailing padding/alignment effects, which the standard does not fix from `sizeof(int)` alone.


Replacing a base subobject in place

Prompt:
Assume ISO C++20. Is the marked call defined?
```cpp
#include <new>
struct B{virtual ~B()=default;virtual int f()const{return 1;}};
struct D:B{int f()const override{return 2;}};
void replace(B* p){p->~B();::new((void*)p) B; int n=p->f(); /* marked */}
int main(){alignas(D) unsigned char s[sizeof(D)];D*d=::new((void*)s)D;replace(d);}
```
Account for transparent replaceability and give the smallest placement-new change that makes the call valid without `std::launder`.

System: Apply ISO C++20 lifetime and transparent-replaceability rules.

classification: Definedness of the marked use.
  0 — Calls the use defined because the address is unchanged.
  1 — States that using `p` directly for the call is not valid via transparent replacement when the old object was a base-class subobject.

minimal_fix: Correct local placement-new target.
  0 — Suggests only casting differently or reconstructing `B` again.
  1 — Changes the placement new to construct `D` (for example `::new ((void*)p) D`), so the old complete `D` is transparently replaced and the existing pointer can denote the new corresponding object without laundering.


List initialization constructor priority

Prompt:
Assume ISO C++20. What exact text is printed?
```cpp
#include <iostream>
struct X{X(){std::cout<<"D";} X(int){std::cout<<"I";} X(std::initializer_list<int>){std::cout<<"L";}};
int main(){X a; X b{}; X c{1}; X d(1);}
```

System: Give exact output using C++20 initialization rules.

exact_output: Constructor sequence.
  0 — Gives anything other than `DDLI`.
  1 — Gives exactly `DDLI`.

initialization_reasoning: Constructor selected for each declaration.
  0 — Claims empty braces prefer the initializer-list constructor.
  1 — Explains that default- and empty-list-initialization select the default constructor here; nonempty list-initialization gives initializer-list constructors first priority; parentheses with `1` select `X(int)`.


Auto forwarding-reference deduction

Prompt:
Assume ISO C++20. Does this declaration compile, and what type is deduced for `x`?
```cpp
const int a=1;
auto&& x=a;
```

System: State the exact deduced declared type including cv/ref qualifiers.

deduced_type: Exact type.
  0 — Gives `int&&`, `const int&&`, or `int&`.
  1 — States that it compiles and `x` has type `const int&`.

deduction_reason: Reference collapsing and lvalue deduction.
  0 — Treats `auto&&` as always an rvalue reference.
  1 — Explains that because the initializer is an lvalue, `auto` deduces as `const int&`; reference collapsing turns `const int& &&` into `const int&`.


Discarded constexpr-if statement

Prompt:
Assume ISO C++20. Is the program well-formed?
```cpp
template<class T> void f(T){static_assert(sizeof(T)==0);}
int main(){ if constexpr(false) f(0); }
```
Explain whether the function template specialization is instantiated.

System: Apply template instantiation rules to a non-template enclosing function.

well_formedness: Compilation result.
  0 — Says `f<int>` is instantiated and the assertion fails.
  1 — States that the program is well-formed.

instantiation_reasoning: Effect of the discarded statement.
  0 — Claims discarded statements are not parsed or need not be syntactically valid.
  1 — Explains that the false `if constexpr` substatement is discarded and the call does not cause `f<int>` to be instantiated; the dependent `static_assert` therefore is not evaluated. The discarded code must still satisfy applicable parsing/non-dependent checks.


Virtual dispatch with static default argument

Prompt:
Assume ISO C++20. What exact text is printed?
```cpp
#include <iostream>
struct A{virtual void f(int x=1){std::cout<<"A"<<x;}};
struct B:A{void f(int x=2)override{std::cout<<"B"<<x;}};
int main(){B b; A* p=&b; p->f();}
```

System: Separate virtual function selection from default-argument binding.

exact_output: Exact output.
  0 — Gives anything other than `B1`.
  1 — Gives exactly `B1`.

dispatch_reason: Two different static/dynamic decisions.
  0 — Uses B's default 2 because B's override runs.
  1 — Explains that virtual dispatch selects `B::f`, while default arguments are bound from the static type of the call expression (`A*`), supplying 1.


Exception unwinding destructor order

Prompt:
Assume ISO C++20. What exact text is printed?
```cpp
#include <iostream>
struct X{~X(){std::cout<<"X";}};
int main(){try{X x; throw 1;}catch(int){std::cout<<"C";}std::cout<<"E";}
```

System: Give exact observable order.

exact_output: Destructor, handler, continuation sequence.
  0 — Gives anything other than `XCE`.
  1 — Gives exactly `XCE`.

unwinding_reason: Why destruction precedes handler body.
  0 — Places destruction after the catch or at end of main.
  1 — Explains that stack unwinding destroys automatic `x` before control enters the matching handler; the catch prints `C`, then execution continues after the handler and prints `E`.


Transparent replacement with const member

Prompt:
Assume ISO C++20. Is `p` usable after the placement new without laundering?
```cpp
#include <new>
struct X{const int n;};
int main(){X x{1}; X* p=&x; x.~X(); ::new((void*)&x) X{2}; return p->n;}
```
If not, state the required expression and resulting return value.

System: Apply C++20 transparent replacement; do not apply obsolete pre-C++20 folklore.

answer: Pointer usability and returned value.
  0 — Says `std::launder(p)` is required solely because `X` has a const data member.
  1 — States that in C++20 the complete object is transparently replaced, `p` automatically denotes the new `X`, and the program returns 2 without laundering.

lifetime_reason: Applicability of transparent replacement.
  0 — Claims const subobjects categorically prevent transparent replacement in C++20.
  1 — Explains that old and new objects are complete objects of the same type, overlay exactly, and satisfy C++20's transparent-replaceability conditions; the const member does not itself defeat replacement.


Inactive union member read

Prompt:
Assume ISO C++20. Is the read defined?
```cpp
union U{int i; float f;};
int main(){U u;u.i=0;return u.f==0.0f;}
```

System: Classify under ISO C++20, independent of compiler extensions.

classification: Definedness of reading `u.f`.
  0 — Calls it a defined bit reinterpretation yielding floating zero.
  1 — States that reading the inactive `float` member is undefined behavior under ISO C++20.

union_reason: Active member and exceptions.
  0 — Invokes C-style type punning as a general C++ permission.
  1 — Explains that assignment makes `i` active; `f` is inactive, and no common-initial-sequence exception applies to scalar members. Compiler extensions do not change the ISO answer.


Named forwarding reference value category

Prompt:
Assume ISO C++20. Which overload is called?
```cpp
#include <iostream>
void f(int&){std::cout<<"L";} void f(const int&){std::cout<<"C";} void f(int&&){std::cout<<"R";}
template<class T> void g(T&& x){f(x);f(static_cast<T&&>(x));}
int main(){g(1);}
```

System: Give exact output and deduction/value-category reasoning.

exact_output: Overload sequence.
  0 — Gives anything other than `LR`.
  1 — Gives exactly `LR`.

forwarding_reason: Named variable and cast categories.
  0 — Treats named `x` as an xvalue merely because its type is `int&&`.
  1 — Explains that `T` is `int`; named expression `x` is an lvalue and calls `f(int&)`, while `static_cast<T&&>(x)` is an xvalue and calls `f(int&&)`.


Explicit constructor in braced argument

Prompt:
Assume ISO C++20. Does this compile?
```cpp
struct X{explicit X(int){}};
void f(X){}
int main(){f({1});}
```
Distinguish direct-list-initialization from copy-list-initialization of a parameter.

System: Apply copy-list-initialization rules precisely.

compilation: Whether the call is well-formed.
  0 — Says braces directly initialize `X` and therefore allow the explicit constructor.
  1 — States that the call is ill-formed.

initialization_reason: Why explicit is disallowed.
  0 — Attributes rejection to narrowing or missing conversion.
  1 — Explains that the braced argument copy-list-initializes the `X` parameter; if overload resolution selects an explicit constructor in copy-list-initialization, the initialization is ill-formed.


Slice aliases array storage

Prompt:
Assume Zig 0.13.0 in Debug mode. What exact text is printed?
```zig
const std=@import("std");
pub fn main() !void {
 var a:[3]u8=.{1,2,3};
 const s=a[0..];
 a[1]=9;
 std.debug.print("{d}-{d}\n",.{s[1],s.len});
}
```

System: Answer for Zig 0.13.0 exactly.

exact_output: Exact printed line.
  0 — Gives anything other than `9-3`.
  1 — Gives exactly `9-3`.

alias_reason: Slice representation and mutation.
  0 — Claims slicing copies the array.
  1 — Explains that `s` is a slice referencing `a`'s storage with length 3, so the later write to `a[1]` is observed through `s[1]`.


Runtime value passed to comptime parameter

Prompt:
Assume Zig 0.13.0. Does this compile?
```zig
const std=@import("std");
fn f(comptime n:usize) usize { return n+1; }
pub fn main() void { var x:usize=3; std.debug.print("{}",.{f(x)}); }
```
Explain the stage mismatch, if any.

System: Distinguish compile-time-known from runtime values in Zig 0.13.0.

compilation: Whether the call is legal.
  0 — Says the compiler evaluates `f` at runtime.
  1 — States that it fails to compile because `x` is runtime-known and cannot satisfy a `comptime` parameter.

stage_reason: What `comptime` requires.
  0 — Claims `var` values are always compile-time-known when initialized by literals.
  1 — Explains that a `comptime` parameter requires its argument value at compile time; declaring mutable runtime storage prevents using `x` as such an argument, despite literal initialization.


defer and errdefer ordering

Prompt:
Assume Zig 0.13.0. What exact text is printed?
```zig
const std=@import("std");
fn f() !u8 { errdefer std.debug.print("E",.{}); defer std.debug.print("D",.{}); return error.Bad; }
pub fn main() void { _=f() catch |e| {std.debug.print("C:{s}",.{@errorName(e)}); return;}; }
```

System: Track scope exit and error return order.

exact_output: Exact text.
  0 — Gives anything other than `DEC:Bad`.
  1 — Gives exactly `DEC:Bad`.

cleanup_reason: LIFO cleanup and catch.
  0 — Places the catch before cleanup or omits one cleanup.
  1 — Explains that returning an error runs both deferred actions in reverse registration order: ordinary `defer` prints `D`, then `errdefer` prints `E`; the caller's catch then prints `C:Bad`.


Checked versus wrapping integer addition

Prompt:
Assume Zig 0.13.0 in Debug mode. What happens?
```zig
const std=@import("std");
pub fn main() void { var x:u8=255; x+=1; std.debug.print("{}",.{x}); }
```
Then state how the behavior differs if `x +%= 1` replaces `x += 1`.

System: Answer by build-mode arithmetic semantics.

two_results: Checked and wrapping forms.
  0 — Says both forms wrap to zero.
  1 — States that `+=` overflows and traps/panics in Debug mode, while `+%=` performs wrapping addition and prints `0`.

operator_reason: Explicit wrapping operator distinction.
  0 — Attributes the difference to unspecified machine behavior.
  1 — Explains that ordinary integer arithmetic is safety-checked in Debug mode, whereas `%` arithmetic operators explicitly wrap modulo 2^8.


Catch expression type and fallback

Prompt:
Assume Zig 0.13.0. Does this compile?
```zig
fn f(x:anyerror!u8) u8 { return x catch 7; }
pub fn main() void { const a:u8=f(error.Bad); _=a; }
```
State the value assigned to `a`.

System: Apply Zig error-union and catch-expression semantics.

result: Compilation and assigned value.
  0 — Says the error propagates from `f` or the program fails to compile.
  1 — States that it compiles and `a` is 7.

catch_reason: Error-union unwrapping.
  0 — Treats `catch` as executing only after a panic.
  1 — Explains that `catch` unwraps a success payload or evaluates its fallback on an error; `error.Bad` selects the `u8` fallback 7, making `f` return an ordinary `u8`.


Pointer to local variable escape

Prompt:
Assume Zig 0.13.0. Is the pointer returned by `f` valid to dereference in the caller?
```zig
fn f() *const u8 { var x:u8=3; return &x; }
```
Give the compilation or lifetime diagnosis; do not assume an optimizer extension.

System: Apply Zig's compile-time escape analysis and lifetime rules.

diagnosis: Validity of escaping local address.
  0 — Says the pointer safely refers to heap-promoted storage.
  1 — States that returning a pointer to the local runtime variable is invalid and is rejected/diagnosed because the pointee's lifetime ends when `f` returns.

lifetime_reason: Storage duration.
  0 — Claims Zig automatically heap-allocates escaping locals.
  1 — Explains that `x` has function-local storage and Zig does not implicitly heap-promote it; a caller dereference would outlive the object.


Packed struct bit size

Prompt:
Assume Zig 0.13.0. What is `@sizeOf(T)`?
```zig
const T=packed struct { a:u3, b:u5, c:u8 };
```
Give the answer in bytes and explain why ordinary field alignment does not add padding.

System: Use Zig packed-struct layout rules.

size: Exact byte size.
  0 — Gives anything other than 2 bytes.
  1 — States `@sizeOf(T) == 2`.

layout_reason: Bit accounting.
  0 — Adds ordinary struct padding between fields.
  1 — Explains that the packed fields occupy 3+5+8=16 bits contiguously, yielding two bytes, without ordinary per-field alignment padding.


Exhaustive enum switch

Prompt:
Assume Zig 0.13.0. Does this switch compile?
```zig
const E=enum{a,b,c};
fn f(e:E)u8{return switch(e){.a=>1,.b=>2};}
```
Give the decisive semantic requirement.

System: Apply Zig switch exhaustiveness rules.

compilation: Switch validity.
  0 — Says unmatched `.c` implicitly traps or yields zero.
  1 — States that compilation fails because `.c` is not handled and there is no `else`.

exhaustiveness: Required coverage.
  0 — Treats enum switches as non-exhaustive statement constructs.
  1 — Explains that a Zig `switch` must cover all possible values of the enum (or include an appropriate `else`), especially because it is an expression producing `u8`.


Optional orelse payload

Prompt:
Assume Zig 0.13.0. What exact text is printed?
```zig
const std=@import("std");
pub fn main() void {
 const x:?u8=null;
 const y=x orelse 9;
 std.debug.print("{}",.{y});
}
```

System: Give exact output and resulting type.

result: Output and value.
  0 — Gives anything other than `9`.
  1 — States that it prints `9` and `y` is an ordinary `u8`.

optional_reason: Fallback selection.
  0 — Claims `y` remains null or has type `?u8` necessarily.
  1 — Explains that `orelse` unwraps a present optional payload or evaluates the fallback for null; here null selects 9.


Comptime type parameter and literal coercion

Prompt:
Assume Zig 0.13.0. Does this compile?
```zig
fn f(comptime T:type,x:T)T{return x;}
pub fn main()void{const x=f(u16,3);_ = x;}
```
State the inferred type and value of `x`.

System: Apply peer/type-context coercion for comptime integer literals.

result: Compilation, type, and value.
  0 — Says the integer literal's default type forces `comptime_int` or `i32`.
  1 — States that it compiles; `x` has type `u16` and value 3.

coercion_reason: Parameter context.
  0 — Claims generic parameters cannot supply a coercion context.
  1 — Explains that `T` is fixed at compile time as `u16`, so parameter `x:T` provides the context that coerces the comptime integer literal 3 to `u16`.


V array assignment cloning

Prompt:
Assume V 0.4.10. What exact text is printed?
```v
fn main(){ mut a := [1,2,3]; b := a; a[0]=9; println('${a[0]} ${b[0]}') }
```
Explain V array assignment semantics.

System: Answer for V 0.4.10 language semantics.

exact_output: Exact line.
  0 — Gives anything other than `9 1`.
  1 — Gives exactly `9 1`.

copy_reason: Value semantics of arrays.
  0 — Claims `b` necessarily aliases `a`'s mutable elements.
  1 — Explains that ordinary V array assignment produces an independent array value/copy for this case, so mutating `a[0]` does not change `b[0]`.


No implicit string-to-int conversion

Prompt:
Assume V 0.4.10. Does this compile?
```v
fn f(x int) int { return x+1 }
fn main(){ println(f('3')) }
```
State whether V performs the requested implicit conversion.

System: Use V's strict typing rules.

compilation: Argument type compatibility.
  0 — Says the string is implicitly parsed as integer 3.
  1 — States that it does not compile because a string cannot be passed where `int` is required without explicit conversion/parsing.

typing_reason: No implicit coercion.
  0 — Predicts runtime parse failure.
  1 — Explains that V checks the mismatch statically and does not provide an implicit string-to-integer conversion at the call.


Option fallback block

Prompt:
Assume V 0.4.10. What exact text is printed?
```v
fn f() ?int { return none }
fn main(){ x := f() or { 7 }; println(x) }
```

System: Apply V option propagation/fallback semantics.

result: Exact output.
  0 — Gives anything other than `7` or says an unhandled option aborts.
  1 — States that it prints `7`.

option_reason: Role of the `or` block.
  0 — Says `none` is converted to integer zero.
  1 — Explains that `f` returns no value, so the `or` block supplies 7, which becomes the unwrapped integer assigned to `x`.


Immutable array append

Prompt:
Assume V 0.4.10. Does this compile?
```v
fn main(){ a := [1,2,3]; a << 4 }
```
Explain the mutability requirement.

System: Apply V variable mutability rules.

compilation: Whether append is allowed.
  0 — Says arrays are mutable regardless of binding.
  1 — States that it fails to compile because `a` was not declared `mut`.

mutability_reason: Mutation of bound value.
  0 — Treats `<<` as producing a new array without modifying `a`.
  1 — Explains that `a << 4` mutates/appends to the array and therefore requires `mut a := ...`.


V value receiver method

Prompt:
Assume V 0.4.10. What exact text is printed?
```v
struct S { x int }
fn (s S) val() int { return s.x }
fn main(){ s:=S{x:4}; println(s.val()) }
```

System: Give exact output and receiver interpretation.

output: Exact output.
  0 — Gives anything other than `4`.
  1 — States that it prints `4`.

receiver_reason: Method receiver value access.
  0 — Claims a mutable or pointer receiver is required merely to read a field.
  1 — Explains that `(s S)` is a value receiver and may read the immutable field `x`; no mutation or pointer receiver is needed.


Generic type inference

Prompt:
Assume V 0.4.10. Does this compile?
```v
fn id[T](x T) T { return x }
fn main(){ x:=id(3); println(x) }
```
State the inferred type and output.

System: Apply V generic call inference for the stated version.

result: Compilation, type, output.
  0 — Says explicit `[int]` is mandatory or gives a non-integer result.
  1 — States that it compiles, infers `T` as `int`, and prints `3`.

inference_reason: Inference from argument.
  0 — Claims the return context alone supplies an unrelated type.
  1 — Explains that the integer argument determines generic parameter `T=int`, so the return type is also `int`.


Map missing-key fallback

Prompt:
Assume V 0.4.10. What exact text is printed?
```v
fn main(){ m:={'a':1}; println(m['b'] or { 9 }) }
```

System: Apply V map indexing with an `or` fallback.

output: Exact line.
  0 — Gives zero, an abort, or anything other than `9`.
  1 — States that it prints `9`.

map_reason: Missing-key handling.
  0 — Claims every missing integer map key silently returns zero even with `or`.
  1 — Explains that key `b` is absent and the attached `or` block supplies the fallback value 9.


Implicit interface satisfaction

Prompt:
Assume V 0.4.10. Does this compile?
```v
interface Speaker { speak() string }
struct Dog {}
fn (Dog) speak() string { return 'woof' }
fn say(s Speaker){println(s.speak())}
fn main(){say(Dog{})}
```
State the output and whether an explicit declaration of conformance is needed.

System: Apply V interface satisfaction rules.

result: Compilation and output.
  0 — Says `Dog` must explicitly declare `implements Speaker`.
  1 — States that it compiles and prints `woof`.

interface_reason: Structural conformance.
  0 — Treats V interfaces as requiring nominal inheritance.
  1 — Explains that `Dog` implicitly satisfies `Speaker` by providing a compatible `speak() string` method; no explicit conformance declaration is required.


Block-scope defer captures variable

Prompt:
Assume V 0.4.10. What exact text is printed?
```v
fn main(){ mut x:=1; { defer { println(x) }; x=4 } }
```
State when the deferred block runs and what value it observes.

System: Track V defer execution at scope exit.

output: Exact output.
  0 — Gives `1` or says defer waits until process exit.
  1 — States that it prints `4`.

defer_reason: Scope and observed state.
  0 — Claims the value is copied when `defer` is registered.
  1 — Explains that the deferred block runs when the enclosing inner scope exits, after `x=4`, and observes the current variable value 4.


Immutable-by-default local

Prompt:
Assume V 0.4.10. Does this compile?
```v
fn main(){ x:=3; x=4 }
```
If not, identify the exact declaration change needed.

System: Apply V local variable mutability syntax.

compilation: Assignment legality.
  0 — Says ordinary locals are mutable by default.
  1 — States that it fails because `x` is immutable.

fix: Minimal declaration change.
  0 — Proposes changing the type or using a pointer.
  1 — Identifies `mut x := 3` as the needed declaration for the later assignment.


Cross-warp communication with syncwarp

Prompt:
Assume CUDA 12.x, compute capability 8.0, launch `k<<<1,64>>>(out)`. Is the claimed cross-warp result guaranteed?
```cpp
__global__ void k(int*out){__shared__ int s[2];unsigned t=threadIdx.x,w=t>>5,l=t&31;if(l==0)s[w]=100+w;__syncwarp();out[t]=s[w^1];}
```
Explain visibility, conflicting accesses, and the minimal collective replacement.

System: Use CUDA's synchronization and memory-order rules, not likely scheduling.

guarantee: Correctness of cross-warp reads.
  0 — Says `__syncwarp()` guarantees the exchange across both warps.
  1 — States that the result is not guaranteed and the accesses form unsynchronized cross-warp read/write races.

fix: Minimal synchronization primitive.
  0 — Suggests another `__syncwarp()` with the same per-warp scope.
  1 — Replaces `__syncwarp()` with `__syncthreads()`, which synchronizes all 64 threads in the block and makes preceding shared writes visible before the reads.


Warp ballot population count

Prompt:
Assume CUDA 12.x and launch `k<<<1,32>>>(out)`. What value is guaranteed in `out[0]`?
```cpp
__global__ void k(int*out){unsigned m=__ballot_sync(0xffffffff,threadIdx.x%3==0);if(threadIdx.x==0)out[0]=__popc(m);}
```

System: Compute the active-lane predicate exactly.

value: Exact population count.
  0 — Gives anything other than 11.
  1 — States that `out[0]` is 11.

lane_count: Predicate accounting.
  0 — Counts only ten multiples or includes lane 32.
  1 — Enumerates or correctly counts lanes 0,3,6,...,30: eleven active lanes whose ballot bits are set, and `__popc` returns 11.


Divergent block barrier

Prompt:
Assume CUDA 12.x, compute capability 8.0, launch `k<<<1,64>>>`. Is this barrier use valid?
```cpp
__global__ void k(){if(threadIdx.x<32){__syncthreads();}}
```
State the precise consequence.

System: Apply collective barrier participation requirements.

classification: Validity of conditional barrier.
  0 — Says the first warp may synchronize independently at `__syncthreads()`.
  1 — States that the barrier is invalid because not all non-exited threads in the block reach it; behavior is undefined and may deadlock.

scope_reason: Block-wide nature.
  0 — Treats `__syncthreads` as warp-scoped.
  1 — Explains that `__syncthreads()` is a block-wide collective; the branch is non-uniform across the 64-thread block, so 32 threads wait for participants that never arrive.


Shuffle XOR partner lane

Prompt:
Assume CUDA 12.x and launch `k<<<1,32>>>(out)`. What exact permutation is written?
```cpp
__global__ void k(int*out){unsigned x=threadIdx.x;out[x]=__shfl_xor_sync(0xffffffff,x,1);}
```
Give a formula for every lane.

System: State the exact lane mapping.

permutation: Exact value per lane.
  0 — Gives a rotation or any mapping other than adjacent-pair exchange.
  1 — States `out[x] = x ^ 1` for lanes 0 through 31: 0/1, 2/3, ..., 30/31 exchange values.

shuffle_reason: Meaning of XOR lane mask.
  0 — Claims the operation XORs the data value with 1.
  1 — Explains that lane mask 1 XORs the caller's lane index to choose the source lane; all lanes named in the full mask participate.


Atomic increment final value and ordering

Prompt: Assume CUDA 12.x. A kernel performs `atomicAdd(&counter,1)` on a global-memory `unsigned int counter` from each of exactly 1,000 threads, with no other counter accesses during the kernel. `counter` is initialized to 0 and does not overflow. After the kernel has completed and the host synchronizes, what value is guaranteed? Does atomicity guarantee any ordering among threads beyond that result?

System: Separate atomic modification order from execution ordering.

final_value: Exact synchronized result.
  0 — Gives any value other than 1000 or calls the final count nondeterministic.
  1 — States the final value is guaranteed to be 1000.

ordering_scope: What atomicity does not imply.
  0 — Claims the atomics impose a deterministic thread execution order or a block/global barrier.
  1 — Explains that each read-modify-write is atomic and contributes once to the counter's modification order, but this does not establish a deterministic order of participating threads or act as a general barrier for unrelated accesses.


CUDA built-in dimensions arithmetic

Prompt:
Assume CUDA 12.x, launch `k<<<2,32>>>`, and `out` has two integers initialized to zero.
```cpp
__global__ void k(int*out){if(threadIdx.x==0)out[blockIdx.x]=gridDim.x*blockDim.x+blockIdx.x;}
```
After synchronization, what are `out[0]` and `out[1]`?

System: Compute exact built-in values for the launch.

values: Both exact values.
  0 — Gives neither value correctly.
  1 — Gives one of `out[0]=64` or `out[1]=65` correctly.
  2 — States `out[0]=64` and `out[1]=65`.

launch_reason: Built-in variable substitution.
  0 — Uses total threads as 32 or confuses block and thread indices.
  1 — Explains `gridDim.x=2`, `blockDim.x=32`, and only thread 0 in each block writes, yielding 64 plus the block index.


Threadfence block visibility scope

Prompt: Assume CUDA 12.x, compute capability 8.0. Is `__threadfence_block()` by thread 0 sufficient to make its preceding global-memory write visible to thread 0 of a different block that subsequently reads the location, absent any other synchronization?

System: Distinguish ordering scope from inter-block synchronization.

answer: Cross-block guarantee.
  0 — Says the fence guarantees visibility to every block.
  1 — States that no cross-block visibility/order guarantee follows; the reader may observe the old value and the unsynchronized accesses can race.

scope_reason: Fence scope and missing handshake.
  0 — Treats any fence as a grid-wide barrier.
  1 — Explains that `__threadfence_block()` orders the calling thread's memory operations only with respect to threads in its own block; it neither synchronizes blocks nor provides a communication handshake to the other block.


Warp shuffle reduction

Prompt:
Assume CUDA 12.x, launch `k<<<1,32>>>(out)`. What value does lane 0 write?
```cpp
__global__ void k(int*out){unsigned x=threadIdx.x+1;for(int d=16;d>0;d>>=1)x+=__shfl_down_sync(0xffffffff,x,d);if(threadIdx.x==0)out[0]=x;}
```

System: Compute the warp reduction exactly.

value: Exact reduction.
  0 — Gives anything other than 528.
  1 — States lane 0 writes 528.

reduction_reason: Sum represented by the shuffle stages.
  0 — Sums lane indices 0 through 31 to 496 or ignores the +1.
  1 — Explains that the shuffle-down tree accumulates initial values 1 through 32 in lane 0, whose sum is 32*33/2 = 528.


UVA versus pageable host accessibility

Prompt: Assume CUDA 12.x. May a kernel directly dereference ordinary pageable host memory obtained by `malloc` merely because unified virtual addressing is enabled? Give the portable answer and distinguish address unification from memory accessibility.

System: Answer for portable CUDA behavior, not a platform-specific extension.

answer: Whether malloc memory is device-accessible.
  0 — Says UVA makes every host pointer directly dereferenceable by a kernel.
  1 — States that ordinary pageable `malloc` memory is not thereby device-accessible; direct kernel dereference is not portably valid.

uva_reason: Address-space naming versus allocation properties.
  0 — Equates one virtual address with automatic residency/mapping.
  1 — Explains that UVA unifies pointer/address identification but does not register, pin, map, or migrate arbitrary pageable allocations; mapped pinned host memory or managed memory requires the corresponding CUDA allocation/registration support.


Global index and grid stride

Prompt: Assume CUDA 12.x and a one-dimensional launch. Give the canonical expression for the unique global linear thread index and the canonical grid-stride-loop increment. Then evaluate both for `blockIdx.x=3`, `blockDim.x=128`, `threadIdx.x=5`, `gridDim.x=20`.

System: Give formulas and exact evaluated integers.

index: Formula and value.
  0 — Does not give `blockIdx.x * blockDim.x + threadIdx.x` or gives a value other than 389.
  1 — Gives global index `blockIdx.x * blockDim.x + threadIdx.x = 389`.

stride: Formula and value.
  0 — Does not give `blockDim.x * gridDim.x` or gives a value other than 2560.
  1 — Gives grid stride `blockDim.x * gridDim.x = 2560`.


Mutable reborrow ending at last use

Prompt:
Assume stable Rust 1.85.0. Does this compile, and why?
```rust
fn main(){let mut x=0;let r=&mut x;let s=&mut *r;*s=1;*r=2;println!("{x}");}
```

System: Apply non-lexical lifetimes and reborrowing.

result_and_reason: Compilation, output, and reborrow lifetime.
  0 — Says overlapping mutable references necessarily reject the program or gives output other than 2.
  1 — States that it compiles and prints 2; `s` is a reborrow of `r`, and its borrow ends after `*s=1`, allowing `r` to be used again under non-lexical lifetimes.


Ref pattern avoids partial move

Prompt:
Assume stable Rust 1.85.0. What exact output is printed?
```rust
fn main(){let x=Some(String::from("a"));match x{Some(ref s)=>print!("{s}"),None=>{}}print!("{}",x.is_some());}
```

System: Track match binding mode and ownership.

answer: Exact output and ownership reason.
  0 — Says `x` is moved or gives output other than `atrue`.
  1 — States it prints `atrue`; `ref s` borrows the inner String rather than moving it, so `x` remains usable after the match.


Block constant evaluation

Prompt:
Assume stable Rust 1.85.0. Is this accepted?
```rust
const X:usize={let a=[1,2,3];a.len()};
fn main(){println!("{X}");}
```
Give the output and explain constant evaluation.

System: Apply stable const-evaluation rules.

answer: Compilation and output.
  0 — Says local bindings are forbidden in const blocks or gives output other than 3.
  1 — States it compiles and prints 3; the const initializer block is evaluated at compile time and array `len` is const-evaluable.


Impl Trait Copy bound

Prompt:
Assume stable Rust 1.85.0. Does this compile?
```rust
fn f(_:impl Copy){}
fn main(){let s=String::from("x");f(s);}
```
Name the unsatisfied bound.

System: Give the concrete trait-bound diagnosis.

diagnosis: Exact bound failure.
  0 — Says it compiles because arguments are moved by value.
  1 — States it fails because `String` does not implement `Copy`; moving `s` is allowed in general but cannot satisfy the explicit `impl Copy` parameter bound.


Rest pattern in fixed array

Prompt:
Assume stable Rust 1.85.0. What exact output is printed?
```rust
fn main(){let a=[10,20,30];let [x,..,y]=a;print!("{x}-{y}");}
```

System: Apply array pattern binding semantics.

answer: Exact output and bindings.
  0 — Gives anything other than `10-30`.
  1 — States it prints `10-30`; `x` binds the first and `y` the last element, while `..` ignores the middle.


Deferred arguments versus closure capture

Prompt:
Assume Go 1.23. What exact text is printed?
```go
package main
import "fmt"
func main(){x:=1;defer fmt.Print(x);x=2;defer func(){fmt.Print(x)}()}
```

System: Track defer evaluation and LIFO order.

answer: Exact output and mechanism.
  0 — Gives anything other than `21`.
  1 — States it prints `21`: deferred calls run LIFO; the closure reads current `x=2`, while the earlier `fmt.Print` argument captured value 1 when deferred.


Append within capacity

Prompt:
Assume Go 1.23. Is `len(s)` guaranteed to be 0 or 1 after this code?
```go
s:=make([]int,0,1);s=append(s,7)
```
Also state `cap(s)`.

System: Give exact slice length and capacity.

answer: Exact slice metadata.
  0 — Gives length or capacity other than 1.
  1 — States `len(s)==1` and `cap(s)==1`; append uses the available slot and returns a slice header with length increased by one.


Approximation element in constraint

Prompt:
Assume Go 1.23. Does this compile?
```go
package p
type MyInt int
func f[T ~int](x T) int{return int(x)}
var _=f(MyInt(3))
```

System: Apply type-set approximation syntax.

answer: Constraint satisfaction and result.
  0 — Says only the predeclared type `int` satisfies `~int`.
  1 — States it compiles and produces 3; `~int` includes defined types whose underlying type is `int`, including `MyInt`.


Buffered values after channel close

Prompt:
Assume Go 1.23. What exact text is printed?
```go
package main
import "fmt"
func main(){c:=make(chan int,1);c<-5;close(c);a,ok1:=<-c;b,ok2:=<-c;fmt.Print(a,ok1,b,ok2)}
```

System: Track receives from a closed buffered channel.

answer: Exact output and receive states.
  0 — Gives anything other than `5true0false`.
  1 — States it prints `5true0false`: closing preserves the queued 5 for the first receive; after the buffer drains, receive yields the zero value and `ok=false`.


Untyped constant overflow at assignment

Prompt:
Assume Go 1.23. Does this compile?
```go
package main
func main(){const n=1<<100;var x int=n;_ = x}
```
Explain representability.

System: Apply arbitrary-precision constant and assignment representability rules.

diagnosis: Compilation and overflow point.
  0 — Says the shift itself overflows or silently truncates.
  1 — States it fails at conversion/assignment to `int`: the untyped constant `1<<100` can be represented as a constant, but is not representable by the implementation's `int` type on any permitted Go target.


C byte size versus bit width

Prompt: Assume ISO C17. What is guaranteed about `sizeof(char)`, `sizeof(unsigned char)`, and `CHAR_BIT`? Is `CHAR_BIT==8` required?

System: Use ISO C terminology for bytes and bits.

answer: Exact size and bit-width guarantees.
  0 — Says `sizeof(char)` may differ from 1 or that C requires 8-bit bytes.
  1 — States `sizeof(char)==sizeof(unsigned char)==1`; `CHAR_BIT` is the number of bits in a byte and is at least 8, but need not equal 8.


Relational comparison of unrelated pointers

Prompt:
Assume ISO C17. Is this comparison defined, and is either result guaranteed?
```c
int a,b; int r=&a < &b;
```

System: Distinguish pointer equality and relational operators.

classification: Relational comparison category.
  0 — Calls it undefined behavior or gives a guaranteed boolean.
  1 — States the comparison has an unspecified result for pointers to unrelated objects; neither true nor false is guaranteed, but evaluating it is not thereby undefined behavior.


Unsigned char increment wrap

Prompt:
Assume ISO C17. What exact integer does `f()` return?
```c
int f(void){unsigned char x=255;return ++x;}
```

System: Apply integer promotions and conversion back on compound update.

answer: Exact return and arithmetic reason.
  0 — Calls it signed overflow or gives 256.
  1 — States it returns 0: `x` is promoted for addition, then the value 256 is converted back to `unsigned char`, wrapping modulo 256 under the stated 8-bit-value range implied by initial max 255.


Pointer representation across object pointer types

Prompt: Assume ISO C17. Is `sizeof(int (*)[10])` required to equal `sizeof(int*)`? Give the portable conclusion.

System: Do not assume a flat ABI.

answer: Portable size relationship.
  0 — Says all object pointer types are required to have the same size.
  1 — States that C17 does not require a pointer to an array of 10 int to have the same size/representation as `int*`; equality is common but not portable.


Mutable lambda value capture

Prompt:
Assume ISO C++20. What exact output is printed?
```cpp
#include <iostream>
int main(){int x=1;auto y=[x]()mutable{return ++x;};std::cout<<y()<<y()<<x;}
```

System: Track captured and outer state.

answer: Exact output and state separation.
  0 — Gives anything other than `231`.
  1 — States it prints `231`: the mutable closure increments its private captured copy from 1 to 2 then 3; outer `x` remains 1.


Guaranteed copy elision with deleted copy

Prompt:
Assume ISO C++20. Does this compile?
```cpp
struct A{A()=default;A(const A&)=delete;};
A f(){return A{};}
int main(){A a=f();}
```

System: Apply mandatory prvalue materialization rules.

answer: Compilation and copy-elision rule.
  0 — Says the deleted copy constructor makes either return or initialization ill-formed.
  1 — States it compiles: the prvalue `A{}` initializes the function result directly, and `f()` initializes `a` directly under guaranteed copy elision, so no copy constructor is odr-used.


Competing standard conversions

Prompt:
Assume ISO C++20. Which overload is selected?
```cpp
void f(long);void f(double);
int main(){f(1);}
```

System: Apply overload conversion ranking.

answer: Overload resolution result.
  0 — Selects either overload as uniquely better.
  1 — States the call is ambiguous: `int` to `long` and `int` to `double` are both standard conversion sequences of conversion rank, with neither better.


Character literal type in C++

Prompt: Assume ISO C++20. What does `sizeof('a')` equal, in units of bytes? Contrast this with C.

System: Answer for C++20 and note the requested C contrast.

answer: C++ value and C distinction.
  0 — Says C++ ordinary character literals have type `int`.
  1 — States `sizeof('a') == 1` in C++ because `'a'` has type `char`; in C an ordinary character constant has type `int`, so its size is `sizeof(int)`.


Zig bit size versus ABI size

Prompt: Assume Zig 0.13.0. What are `@bitSizeOf(u7)` and `@sizeOf(u7)`?

System: Give exact bit and byte quantities.

answer: Exact two values.
  0 — Does not give both 7 bits and 1 byte.
  1 — States `@bitSizeOf(u7)==7` and `@sizeOf(u7)==1` byte.


Mutable pointer coercion to const

Prompt:
Assume Zig 0.13.0. Does this compile?
```zig
fn f(x:*const u8)u8{return x.*;}
pub fn main()void{var x:u8=4;const y=f(&x);_ = y;}
```

System: Apply pointer constness coercion.

answer: Compilation and value.
  0 — Says `*u8` cannot be passed as `*const u8`.
  1 — States it compiles and `y==4`; a mutable pointer may coerce to a const pointer for read-only access.


Typed left shift

Prompt:
Assume Zig 0.13.0. What exact value does this compile-time expression produce?
```zig
const x=@as(u8,3)<<2;
```

System: Give exact type and value.

answer: Exact value and type.
  0 — Gives a value other than 12 or a type other than u8.
  1 — States `x` has type `u8` and value 12.


Tagged union inactive field assignment

Prompt:
Assume Zig 0.13.0. Does this compile?
```zig
const U=union(enum){a:u8,b:u16};
pub fn main()void{var u=U{.a=3};u.b=4;}
```
Classify the direct field assignment when `.a` is active.

System: Apply tagged-union active-field safety rules.

diagnosis: Legality of assigning inactive field directly.
  0 — Says direct assignment switches the active tag to `.b`.
  1 — States the code is invalid/traps under safety because `.b` is not the active field; switching variants requires assigning a whole union value such as `u=U{.b=4}`.


V string byte length

Prompt:
Assume V 0.4.10. What exact output is printed?
```v
fn main(){ s:='abc'; println(s.len) }
```

System: Give exact output for ASCII input.

answer: Exact output and unit.
  0 — Gives anything other than 3.
  1 — States it prints 3; for this ASCII string the byte length is three.


Mutable field on immutable struct binding

Prompt:
Assume V 0.4.10. Does this compile?
```v
struct S { mut: x int }
fn main(){ s:=S{}; s.x=1 }
```
Account for both field and variable mutability.

System: Apply V nested mutability requirements.

answer: Compilation and minimal fix.
  0 — Says the mutable field declaration alone permits mutation through immutable `s`.
  1 — States it fails because `s` itself is immutable; declare `mut s := S{}` (with the field already in `mut:`) to permit `s.x=1`.


V array slice length

Prompt:
Assume V 0.4.10. What exact output is printed?
```v
fn main(){ a:=[1,2,3]; println(a[1..].len) }
```

System: Evaluate slice bounds exactly.

answer: Exact result.
  0 — Gives anything other than 2.
  1 — States it prints 2 because the slice from index 1 to the omitted exclusive end contains elements 2 and 3.


V if expression value

Prompt:
Assume V 0.4.10. Does this compile?
```v
fn main(){ x:=if true {1}else{2}; println(x) }
```
Give the output and classify `if` here.

System: Apply V expression typing.

answer: Compilation, output, expression form.
  0 — Says V `if` cannot yield a value or gives output other than 1.
  1 — States it compiles and prints 1; the `if` is used as an expression and both branches yield compatible integer values.


Warp broadcast from lane zero

Prompt:
Assume CUDA 12.x and launch `k<<<1,32>>>(out)`. What does lane 7 write?
```cpp
__global__ void k(int*out){int x=threadIdx.x;out[x]=__shfl_sync(0xffffffff,x,0);}
```

System: Compute the exact shuffle source.

answer: Exact written value.
  0 — Gives anything other than 0.
  1 — States lane 7 writes 0 because every participating lane reads lane 0's value.


Fence without execution synchronization

Prompt: Assume CUDA 12.x. Within one block, thread 0 writes shared memory, calls `__threadfence_block()`, and thread 1 reads without a barrier or atomic handshake. Is the read guaranteed to see the write?

System: Separate a fence from a collective barrier.

answer: Visibility guarantee.
  0 — Says the fence alone forces thread 1 to wait and observe the write.
  1 — States the read is not guaranteed and the accesses remain unsynchronized; `__threadfence_block()` orders the calling thread's memory operations but is not an execution barrier or handshake.


CUDA launch cardinality

Prompt: Assume CUDA 12.x and launch `k<<<3,10>>>(out)`. How many threads execute the kernel body, and what is the maximum one-dimensional global index `blockIdx.x*blockDim.x+threadIdx.x`?

System: Give exact count and maximum index.

answer: Both exact integers.
  0 — Gets both values wrong.
  1 — Gives either 30 threads or maximum index 29.
  2 — States 30 threads execute and the maximum global index is 29.


Block barrier is not grid barrier

Prompt: Assume CUDA 12.x. Is `__syncthreads()` a grid-wide barrier when a kernel has multiple blocks? If not, can it by itself make a producer in block 0 safely hand data to a consumer in block 1 within the same kernel launch?

System: State synchronization scope and consequence.

answer: Scope and cross-block consequence.
  0 — Calls it grid-wide or says matching calls in both blocks synchronize with each other.
  1 — States `__syncthreads()` synchronizes only threads of one block and cannot by itself implement a safe block-0 to block-1 handoff; separate kernel launches, cooperative-grid synchronization under its requirements, or a correct atomic protocol is needed.