假设我有以下代码:
int i = 0;
func(i++, i++);
Run Code Online (Sandbox Code Playgroud)
在返回值后立即发生增量?是否保证第一个参数为0,第二个参数为1?
执行此操作后,值会是多少?
#include <stdio.h>
int main() {
int *a = 0;
int *b = 3;
*a++ = *b++;
printf("%d", a);
printf("%d", b);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码给了我一个分段错误。
我执行了以下代码.
int main(void)
{
int c;
c=0;
printf("%d..%d..%d \n", c,c,c);
c=0;
printf("%d..%d..%d \n", c,c,c++);
c=0;
printf("%d..%d..%d \n", c,c++,c);
c=0;
printf("%d..%d..%d \n", c++,c,c);
return 0;}
Run Code Online (Sandbox Code Playgroud)
我期望输出为
0..0..0
1..1..0
0..1..0
0..0..0
但是输出(用gcc编译)是
0..0..0
1..1..0
1..0..1
0..1..1
我的期望有什么问题?在gcc中,评估顺序是从右到左.是吗?
我们来看第一个代码:
以下代码显示以下值n=10:
#include<iostream>
int main()
{
int n=10;
int*p=&n;
*p++;
std::cout<<n;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
以下代码显示以下值n=11:
#include<iostream>
int main()
{
int n=10;
n++;
std::cout<<n
return 0;
}
Run Code Online (Sandbox Code Playgroud) 确实很简单.
int main()
{
int n,i,j;
n = 20;
i = 0;
char ch[8];
do
{
ch[i] = (n%2) + '0';
n /= 2;
// SIMPLE WAY
if(n != 0)
i++;
}
while(n != 0);
for(j=0; j<=i; j++)
{
printf("%c",ch[i-j]);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但我不喜欢这种方式
我尝试了下面的方法,但代码很糟糕
int main()
{
int n,i,j;
n = 20;
i = 0;
char ch[8];
do
{
ch[i] = (n%2) + '0';
n /= 2;
}
while(n != 0 && i++); // THIS
for(j=0; j<=i; j++) …Run Code Online (Sandbox Code Playgroud) 我写了一个简单的函数来计算目录中非隐藏文件的数量.但是我注意到,当我++以前增加计数值时,我得到了奇怪的结果,比如负数和非常大的数字.当我切换*count++;到*count = *count + 1;函数行为时,我的行为符合我的预期.有人可以解释这种行为吗?
要使用此示例程序,请将目录路径作为第一个参数传递.
#include <stdio.h>
#include <dirent.h>
int count_files_directory(unsigned int *count, char *dir_path)
{
struct dirent *entry;
DIR *directory;
/* Open the directory. */
directory = opendir(dir_path);
if(directory == NULL)
{
perror("opendir:");
return -1;
}
/* Walk the directory. */
while((entry = readdir(directory)) != NULL)
{
/* Skip hidden files. */
if(entry->d_name[0] == '.')
{
continue;
}
printf("count: %d\n", *count);
/* Increment the file count. */
*count++;
}
/* Close the …Run Code Online (Sandbox Code Playgroud) ++*var ++和++ var ++之间有什么区别?为什么++*var ++正在工作而++ var ++结果与C中的左值必需错误?
我很好奇,发现当前的一段代码不起作用,但我无法弄清楚原因:
#include <stdio.h>
void main(){
int a = 42;
printf("%d\n", ++a++);
}
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎不是一个错误的语法.有人可以解释错误输出吗?
first.c: In function ‘main’:
first.c:5:17: error: lvalue required as increment operand
printf("%d\n", ++a++);
Run Code Online (Sandbox Code Playgroud) 以下程序的输出不应该是 -
2 3 20
相反,它正在显示
3 2 15
任何人都可以解释这背后的原因吗?
#include<stdio.h>
main()
{
int a[5] = {5,1,15,20,25};
int i,j,m;
i = ++a[1];
j = a[1]++;
m = a[i++];
printf("%d %d %d",i,j,m);
}
Run Code Online (Sandbox Code Playgroud) 在这个代码中使用 a--和b++显示分段错误,但如果给予--a和++b它的工作,为什么?!
add(a,b)
{
if (a==0)
return b;
else
return add(a--,b++); //why this line didn't work??!
}
Run Code Online (Sandbox Code Playgroud)