cxgo icon indicating copy to clipboard operation
cxgo copied to clipboard

Bug: Explicit float to int casting for union member variable of int type

Open Yeaseen opened this issue 6 months ago • 1 comments

Source C code:

#include <stdio.h>
union TypePunning {
    int intValue;
};
int main() {
    union TypePunning pun;
    pun.intValue = 1;
    pun.intValue =(int)1.23f;
    printf("Result: %d\n", pun.intValue);
    return 0;
}

Translated Go code:

package main

import (
	"github.com/gotranspile/cxgo/runtime/stdio"
	"os"
)

type TypePunning struct {
	// union
	IntValue int
}

func main() {
	var pun TypePunning
	pun.IntValue = 1
	pun.IntValue = int(1.23)
	stdio.Printf("Result: %d\n", pun.IntValue)
	os.Exit(0)
}

Go Build Failure at type casting

./runner.go:16:21: cannot convert 1.23 (untyped float constant) to type int

Root Cause:

Direct type conversion from float to int is illegal in Go. It should be an explicit conversion.

Yeaseen avatar Aug 31 '24 03:08 Yeaseen