隐式强制转换U32至U8不会引发警告

问题描述

我在Code :: Blocks-gcc上编译了以下代码

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

void test_print(uint8_t test_var);

int main()
{
    uint32_t var = 100000U;

    test_print(var);

    return 0;
}


void test_print(uint8_t test_var)
{
    printf("test_var = %d\n",test_var);
}

为什么它不发出任何警告? 对我来说,这很奇怪,因为我将U32隐式转换为U8。 (应避免这样做,因为在此过程中信息会丢失)

解决方法

您需要将function formatDecimals(num: Number,decimal_places: int): String { //if no decimal places needed,we're done if (decimal_places <= 0) { return Math.round(num).toString(); } //round the number to specified decimals var tenToPower: int = Math.pow(10,decimal_places); var cropped: String = String(Math.round(num * tenToPower) / tenToPower); //add decimal point if missing if (cropped.indexOf(".") == -1) { cropped += ".0"; } //finally,force correct number of zeroes; add some if necessary var halves: Array = cropped.split("."); //grab numbers to the right of the decimal //compare decimal_places in right half of string to decimal_places wanted var zerosNeeded: int = decimal_places - halves[1].length; //number of zeros to add for (var i = 1; i <= zerosNeeded; i++) { cropped += "0"; } return (cropped); } 标志用于gcc,这将在此进行:

-Wconversion

这是[dbush@db-centos7 ~]$ gcc -Wconversion -g -Wall -Wextra -o x1 x1.c x1.c: In function ‘main’: x1.c:11:5: warning: conversion to ‘uint8_t’ from ‘uint32_t’ may alter its value [-Wconversion] test_print(var); -Wall中未包含的标志之一。