如何降低程序可读性(二)

先看两个和结构体相关的例子

struct veg{ int weight,price_per_lb; };
struct veg onion,radish,turnip;
struct veg{ int weight,price_per_lb; }onion,radish,turnip;

虽然第二个例子节省了不少代码,但是明显第一个例子相对赏心悦目一点。

然后我们在第二个例子里加点有意思的东西;

#include   <iostream>   
#include <stdlib.h>
//----------------------------
struct veg{
	int weight, price_per_lb;
	int a[100];
}onion, radish, turnip;


//---------------------------


struct veg twofold(struct veg s){
	for (int j = 0; j < 100; j++) s.a[j] *= 2;
	return s;
}
//---------------------------------
void main(){
	int i;
	for (int i = 0; i< 100; i++) onion.a[i] = 1;
	radish = twofold(onion);
	turnip = radish;
}

程序有错误么?没有,但是你当你读到
onion, radish, turnip

时总是会忍不住往上翻,明明你知道它是结构体对象。与其给你往上翻的时间,你不妨直接将对象定义到你要用到的地方。

#include <iostream>   
#include <stdlib.h>
//----------------------------
struct veg{
	int weight, price_per_lb;
	int a[100];
};

//---------------------------
struct veg twofold(struct veg s){
	for (int j = 0; j < 100; j++) s.a[j] *= 2;
	return s;
}
//---------------------------------
void main(){
	int i;
	struct veg onion, radish, turnip;
	for (int i = 0; i< 100; i++) onion.a[i] = 1;
	radish = twofold(onion);
	turnip = radish;
}

嗯~这样其实感觉上没什么区别,那我们将在加入点东西。

#include   <iostream>   
#include <stdlib.h>
//----------------------------
struct veg{
	int weight, price_per_lb;
	int a[100];


	veg(int n)
	{
		static int num = 0;
		printf("num第%d次初始化\n", num++);


	}
	veg()
	{
		int num_t = 0;
		printf("num_t第%d次初始化\n", num_t++);
	}
	void Funtion()
	{
		printf("End!");
	}
};




//---------------------------
struct veg twofold(struct veg s){
	for (int j = 0; j < 2; j++) s.a[j] *= 2;
	return s;
}
//---------------------------------
void main(){
	struct veg onion(2), radish(1), turnip(0);
	for (int i = 0; i< 100; i++) onion.a[i] = 1;
	radish = twofold(onion);
	turnip = radish;
	struct veg  teacher[3] = { onion, radish, turnip };
	printf(" t_0=%d \
		  \n t_1=%d \
		  \n t_1=%d \n",
		  teacher->a[0],
		  teacher->a[1],
		  teacher->a[2]);
	struct veg onion_t();
	onion.Funtion();
}

这个程序看上去总觉的有点恶心,但是你又找不到哪里是不对的。如过在mian函数夹杂着一条

onion_t.Funtion();
如果没有编译器真的好发现它的存在么,当然这样显然是错误的,因为
struct veg onion_t();//编译器只会认为你在声明一个返回veg的函数onion_t();

上面程序的结果显而易见,static num 会不断叠加,而num_t因为一直被赋值0所以永远输出0;



猜你喜欢

转载自blog.csdn.net/iloveyou418/article/details/79349192