Do not use if statement, so that there is a',' sign between every two adjacent numbers

By chance I saw a very elegant piece of code, just 11 lines of code, but it contains knowledge points such as arrays, pointers, strings, loops, etc.

Not much to say, look at the code:

Requirement, do not use if statement, so that there is a',' sign between two adjacent numbers

#include<stdio.h>
int main()
{
	int a[6]={1,2,3,4,5,6};
	int i;
	for(i=0;i<6;i++)
	{
		printf(",%d"+!i,a[i]);
	 } 
	return 0;
}

This code, without using the if statement, will achieve the requirements of the topic

The key point is the clever use of string and pointer addresses

Strings are also pointers, and pointers store addresses, so ",%d"+1 is equivalent to adding 1 to the first address of the string ",%d", that is,% becomes the first address and a comma will not be printed.

At i = 0,! i = 1;

When i = 1,! i=0 because! Represents the negation.

Therefore, except for i=0 in the first traversal,! i = other than 1, the latter! i=0;

This method uses the least amount of code to complete the requirements, which is amazing.

Guess you like

Origin blog.csdn.net/weixin_49472648/article/details/108126256