This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
unexpected warning about unused variables from anonymous union with a template member
- From: Steve Ward <planet36 at gmail dot com>
- To: gcc-help at gcc dot gnu dot org
- Date: Sat, 5 Dec 2009 22:52:57 -0500
- Subject: unexpected warning about unused variables from anonymous union with a template member
See the attached program.
Command:
g++ -Wunused anonymous_union.cpp
Output:
anonymous_union.cpp: In function 'void print_byte_array_2(T) [with T =
unsigned int]':
anonymous_union.cpp:95:?? instantiated from here
anonymous_union.cpp:38: warning: unused variable 'y'
anonymous_union.cpp:38: warning: unused variable 'byte_array'
Expected output:
none
The four functions do the same thing.? Two use template parameters,
and the other two use non-template parameters.? Two use anonymous
unions, and the other two use named unions.
Warnings about unused variables are printed for the second function
(with a template parameter and anonymous union) but not for the other
three.
g++ --version
g++ (Ubuntu 4.4.1-4ubuntu8) 4.4.1
Steve
#include <stdint.h>
#include <iostream>
#include <iomanip>
template<typename T>
void print_byte_array_1(T x)
{
union
{
T y;
uint8_t byte_array[sizeof(T)];
} u;
u.y = x;
for (unsigned int i = 0; i < sizeof(u.byte_array); ++i)
{
std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(u.byte_array[i]);
}
std::cout << '\n';
}
template<typename T>
void print_byte_array_2(T x)
{
// anonymous union
union
{
T y;
uint8_t byte_array[sizeof(T)];
};
y = x;
for (unsigned int i = 0; i < sizeof(byte_array); ++i)
{
std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(byte_array[i]);
}
std::cout << '\n';
}
void print_byte_array_3(uint32_t x)
{
union
{
uint32_t y;
uint8_t byte_array[sizeof(uint32_t)];
} u;
u.y = x;
for (unsigned int i = 0; i < sizeof(u.byte_array); ++i)
{
std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(u.byte_array[i]);
}
std::cout << '\n';
}
void print_byte_array_4(uint32_t x)
{
// anonymous union
union
{
uint32_t y;
uint8_t byte_array[sizeof(uint32_t)];
};
y = x;
for (unsigned int i = 0; i < sizeof(byte_array); ++i)
{
std::cout << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(byte_array[i]);
}
std::cout << '\n';
}
int main()
{
const uint32_t x = 0x11223344;
print_byte_array_1(x);
print_byte_array_2(x);
print_byte_array_3(x);
print_byte_array_4(x);
return 0;
}
/*
g++ -Wunused anonymous_union.cpp
anonymous_union.cpp: In function 'void print_byte_array_2(T) [with T = unsigned int]':
anonymous_union.cpp:61: instantiated from here
anonymous_union.cpp:38: warning: unused variable 'y'
anonymous_union.cpp:38: warning: unused variable 'byte_array'
g++ --version
g++ (Ubuntu 4.4.1-4ubuntu8) 4.4.1
*/