我试过执行以下程序:
#include <stdio.h>
int main() {
signed char a = -5;
unsigned char b = -5;
int c = -5;
unsigned int d = -5;
if (a == b)
printf("\r\n char is SAME!!!");
else
printf("\r\n char is DIFF!!!");
if (c == d)
printf("\r\n int is SAME!!!");
else
printf("\r\n int is DIFF!!!");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于这个程序,我得到输出:
char是DIFF !!! int是相同的!
为什么我们两者都有不同的输出?
输出应该如下?
char是相同的!int是相同的!
一个键盘连接.
从我从得到的回答这个问题,看来C++继承了这一要求,对于转换short成int从C.执行算术运算时,我可以挑你的大脑,以为什么这是用C首先介绍?为什么不做这些操作short呢?
例如(取自评论中的dyp建议):
short s = 1, t = 2 ;
auto x = s + t ;
Run Code Online (Sandbox Code Playgroud)
x将具有int类型.
我是C ++ 17的新手,正尝试了解decltype关键字及其与的搭配auto。
下面是产生意外结果的代码片段。
#include <typeinfo>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int16_t mid = 4;
auto low = mid - static_cast<int16_t>(2);
auto hi = mid + static_cast<int16_t>(2);
int16_t val;
cin >> val;
val = std::clamp(val,low,hi);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
令人惊讶的是,编译器告诉我clampand low和highare都不匹配int。如果我更改auto为int16_t世界上的所有人都很好,并且所有类型都int16_t符合预期。
我提出这个问题时,为什么不auto投low,并hi于int当所有的类型是int16_t?这是一个很好的用例decltype吗?
即使在阅读cppreference.com之后,我仍然不完全了解其decltype工作原理,所以请原谅我的无知。
我有以下代码:
#include <cstdint>
template <typename T>
T test(T a, T b)
{
float aabb = reinterpret_cast<float>(a - b);
}
int main(int argc, const char *argv[])
{
std::uint8_t a8, b8;
test(a8, b8);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我知道它reinterpret_cast<float>无法工作,并且它在编译时出错.我正在使用该错误,以便编译器告诉我类型a - b.
问题是,在这种情况下,它说的类型a - b是int当两者都是uint8_t (unsigned char).同样的事情发生在uint16_t.但不能与uint32_t它说a - b是unsigned int.
所以,我的问题是:这是预期的行为(unsigned char - unsigned char给出一个int),还是这种奇怪的编译器bug(用GCC和clang测试过)?
在Java中,如果我们划分bytes,shorts或ints,我们总是得到一个int.如果其中一个操作数是long,我们就会得到long.
我的问题是 - 为什么byte或short除法不产生byte或short?为什么总是int?
显然我不是在寻找"因为JLS这么说"的答案,我在Java语言中询问这个设计决策的技术原理.
考虑以下代码示例:
byte byteA = 127;
byte byteB = -128;
short shortA = 32767;
short shortB = -32768;
int intA = 2147483647;
int intB = - -2147483648;
long longA = 9223372036854775807L;
long longB = -9223372036854775808L;
int byteAByteB = byteA/byteB;
int byteAShortB = byteA/shortB;
int byteAIntB = byteA/intB;
long byteALongB = byteA/longB;
int shortAByteB = …Run Code Online (Sandbox Code Playgroud) 考虑这个代码:
val x1: Byte = 0x00
val x2: Byte = 0x01
val x3: Byte = x1 + x2;
Run Code Online (Sandbox Code Playgroud)
这会产生编译错误,因为添加 2 Bytes的结果是Int.
为了解决这个问题,我需要手动将结果转换回一个字节:
val x3: Byte = (x1 + x2).toByte()
Run Code Online (Sandbox Code Playgroud)
这是非常违反直觉的。为什么算术运算符会这样工作?