请参阅此代码段
int main()
{
unsigned int a = 1000;
int b = -1;
if (a>b) printf("A is BIG! %d\n", a-b);
else printf("a is SMALL! %d\n", a-b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这给出了输出:a是SMALL:1001
我不明白这里发生了什么.>运算符如何在这里工作?为什么"a"小于"b"?如果它确实更小,为什么我得到一个正数(1001)作为差异?
请考虑以下代码:
template<bool> class StaticAssert;
template<> class StaticAssert<true> {};
StaticAssert< (-1 < sizeof(int)) > xyz1; // Compile error
StaticAssert< (-1 > sizeof(int)) > xyz2; // OK
Run Code Online (Sandbox Code Playgroud)
为什么是-1 > sizeof(int)真的?
-1提升到unsigned(-1)那时是真的吗unsigned(-1) > sizeof(int)?-1 > sizeof(int)相当于-1 > size_t(4)如果的sizeof(int)的是4,如果是这样的话,为什么-1 > size_t(4)是假的?这个C++标准是否合适?
在VS2013中处理这段小代码,但由于某种原因它没有print.it似乎-1> strlen(str)
任何人都知道我做错了什么
char *str="abcd";
if(-1<strlen(str))
printf("The size of the string is %d", strlen(str));
return 0;
Run Code Online (Sandbox Code Playgroud) 考虑这个C代码:
#include "stdio.h"
int main(void) {
int count = 5;
unsigned int i;
for (i = count; i > -1; i--) {
printf("%d\n", i);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的观察/问题:循环永远不会被执行.但是,如果我将i的数据类型从unsigned int更改为int,则一切都按预期工作.
我一直在考虑使用无符号整数作为当你试图从它们中减去时"环绕"的值.因此,当i为零并且我减去1时,它将回绕到UINT_MAX.而且由于它的价值永远不会消极,这实际上是一个无限循环.(当我将比较从i> -1更改为i> = 0时,这正是发生的情况.)
在我的逻辑中某处有一个错误,因为如果我是无符号的,循环永远不会执行,我将它与-1进行比较.编译器要么以某种方式优化它,要么运行时值的行为与我期望的不同.
为什么循环不能运行?
#include<stdio.h>
#include<conio.h>
void main()
{
if(sizeof(int)>=-2)
printf("True");
else
printf("False");
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用Turbo C++编译这段代码时,它返回False而不是True.但是当我尝试打印int的值时,程序返回2.
这怎么可能 ?而sizeof(int)返回2并且是2> = - 2.
在此程序中,TOTAL_ELEMENTS当不用于for循环时,计算正确.并且第一个printf正确打印.但是,即使循环中的条件为真,第二个printf也无法工作.TOTAL_ELEMENTS回报7.而-1<7-2即-1<5是真实的.那么这里有什么问题?
#include<stdio.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
printf("Total= %d\n", TOTAL_ELEMENTS);
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 在以下代码中
#include <stdio.h>
int main()
{
if (sizeof(int) > -1)
printf("True");
else
printf("False");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到输出为"False"而不是"True".我的理解是sizeof运算符只返回int的大小,在这种情况下为4.
为什么评估条件为假?
我写了一个小程序作为例子来复制我遇到的问题.该程序以这种方式接受和操作两行:
' '),后跟一个数字.'\0'到它.这是最小的程序:
#include <stdio.h>
#include <string.h>
void read(char *text)
{
// create and initialize the line holder
int k = 0;
char line[10];
line[0] = '\0';
for (int i = 0;text[i] != '\0';i++)
{
if (text[i] == '\n')
{
// k now points to the character right after the last assigned one, so put 0 in that place
line[k] = '\0';
// initialize data objects that will hold text and …Run Code Online (Sandbox Code Playgroud)