一道有趣的题目

How can I print 1 to 100 in C++ without a loop, goto or recursion?

link

1. Using the alarm system call.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
int i = 0;
void sig_alarm_handler(int signal) {
    ++i;
    printf("%d
", i);
    if(i < 100)
        alarm(1);
    else
        exit(0);
}
int main() {
    signal(SIGALRM, sig_alarm_handler);
    alarm(1);
    int x;
    scanf(" %d",&x);
    return 0;
}

2. Using fread and fwrite.

#include <stdlib.h>
#include <stdio.h>
int main() {
    FILE* fd = fopen("data.txt", "r");
    char buf[10000];
    size_t n = fread(buf, sizeof(char), 10000, fd);
    fwrite(buf, sizeof(char), n, stdout);
    fflush(stdout);
    fclose(fd);
    return 0;
}

3. Using queued SIGUSR calls.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
int mypid;
void signal_handler(int signal, siginfo_t* siginfo, void* extra) {
    printf("%d
", siginfo->si_int);
    sigval_t signal_value;
    memcpy(&signal_value, &siginfo->si_value, sizeof(signal_value));
    ++signal_value.sival_int;
    if(signal_value.sival_int <= 100)
        sigqueue(mypid, SIGUSR1, signal_value);
    else
        exit(0);
}
int main() {
    mypid = getpid();
    struct sigaction sa;
    bzero(&sa, sizeof(sa));
    sa.sa_sigaction = signal_handler;
    sa.sa_flags = SA_SIGINFO | SA_NODEFER | SA_RESTART;
    sigaction(SIGUSR1, &sa, NULL);
    sigval_t signal_value;
    signal_value.sival_int = 1;
    sigqueue(mypid, SIGUSR1, signal_value);
    sleep(1000);
    return 0;
}

4. Memory mapping a file.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
    int fd = open("data.txt", O_RDONLY);
    struct stat stat_data;
    fstat(fd, &stat_data);
    off_t file_size = stat_data.st_size;
    // Memory map the file
    void* baseaddr = mmap(NULL, file_size, PROT_READ, MAP_PRIVATE, fd, 0);
    // Copy the memory mapped region to stdout
    fwrite((char*)baseaddr, sizeof(char), file_size, stdout);
    fflush(stdout);
    // Unmap the memory mapped region
    munmap(baseaddr, file_size);
    // Close the file
    close(fd);
    return 0;
}

5. The standard template metaprogram

#include <stdio.h>
template<int N>
struct X : X<N-1> {
    X() { printf("%d
", N); }
};
template<>
struct X<0> {};
int main() {
    X<100> x;
    return 0;
}

6. Using a static variable and an array

#include <stdio.h>
struct X {
    static int i;
    X() { ++i; printf("%d
", i); }
};
int X::i = 0;
int main() {
    X arr[100];
    return 0;
}
原文地址:https://www.cnblogs.com/shhu1993/p/5194084.html