I compile this code with g++ -Wall, get no warnings/errors:

#include "stdio.h"

int main() {
        long x = 1000000000000;
        int y = x;
        printf("%ld %d\n", x, y);
        return 0;
}

The output is something one would expect:

1000000000000 -727379968

But shouldn't the compiler prevent from implicit conversion/truncation in this case?

g++ (GCC) 4.1.2 20071124 (Red Hat 4.1.2-42)
有帮助吗?

解决方案

I believe you're looking for -Wconversion which is NOT included in the -Wall. I definitely got the warning in g++ 4.4 and 4.5 but I don't have access to test earlier versions. warning: conversion to 'int' from 'long long int' may alter its value (I used long long because I was generating a 32 bit build where long is still 32 bits).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top